One place for hosting & domains

      Types

      A Guide to API Formats: The Different Types of APIs


      APIs are what keep software connected. Whether you are looking to link your application to others or you want to have smooth communication between services, APIs help bring multiple pieces of an application together.

      Applications and services can be connected in myriad ways, depending on access limitations and communication protocols. APIs have developed several different approaches for making connections to support modern application architectures.

      In this tutorial, learn about what APIs are, the types of APIs that are available, and the various protocols they can use to communicate.

      What is an API?

      An API — short for Application Programming Interface — defines a set of rules by which applications and services can interact.

      APIs are used in a wide variety of contexts. However, often, when people talk about APIs, they are talking about web APIs. These APIs allow for communication between applications and services using the
      HTTP protocol
      .

      Often, web APIs are used for web application servers and web browsers to communicate. However, you may also see web APIs used for communication between different web servers, or between applications on the same server. You may even see web APIs at work between different services acting as parts of the same application. One example of an API enabling communication between different services of the same application, is Kubernetes. The
      Kubernetes API
      is the linchpin to its powerful orchestration system.

      The Four Main Types of APIs

      APIs come in four different modalities. Each of these covers a different access level or, in the case of web APIs, a different usage.

      Which one of these you use depends on your API’s particular needs. The sections below provide descriptions of each kind of API and they can help you decide which is best for your use case. Each section also provides context and examples to make it easier to see how each API model can fit into different use cases.

      Open APIs

      Open APIs, or public APIs, come with limited or no access restrictions. This essentially allows any developer to make requests to these APIs.

      These APIs may have some limits. A developer may have to register an account to receive an API key, for instance. Additionally, limits may be placed on things like the number of requests in a given time frame.

      But overall, open APIs are distinguished by being intended for widespread external use. They are meant for third-party developers to be able to access and make use of the API as they need.

      An example of open APIs are those provided by
      NASA
      . After completing a simple registration for an API key, NASA gives you access to numerous open APIs. NASA’s open APIs include everything from Earth observation images to information about the weather on Mars.

      When to Use an Open API?

      Make your API open when you intend it for public consumption. Open APIs are especially useful when you have information or services you want to make available to the general public.

      These APIs are often used for open source projects and for the dissemination of public knowledge, like NASA and other government agencies.

      Partner APIs

      Partner APIs require authorization of some kind to use. They still allow external access, but are not intended for the general public to have access to. Instead, partner APIs are designed for use by pre-approved individuals, teams, or organizations.

      A partner API may allow public access through a paid subscription or it may limit access to developers with a business relationship. Typically, the developer has an API key, as with open APIs, that require registration. But with partner APIs, keys tend to be given out more sparingly and with more access restrictions.

      An example of a partner API is one that allows two companies to work together. Company A may have an application which Company B has agreed to provide services for. Developers at Company A receive API keys which they can use to access Company B’s API. This allows Company A’s application to make use of Company B’s services while keeping access to these services limited.

      When to Use a Partner API?

      Make your API a partner API when it needs to be accessed externally but that access needs to be limited to authorized users. Partner APIs are ideal for business-to-business services or for subscription-based APIs.

      You are likely to see partner APIs in companies that make use of external services for parts of an application’s functionality. Often, this can be a preferred solution compared to developing services in house. It allows companies to integrate features that have been developed by experts elsewhere into their applications. At the same time, it lets the external experts retain control of their services.

      Internal APIs

      Internal APIs, also called private APIs, disallow external access. Instead, these APIs can only be accessed by developers within a company or even within the particular application to which the API belongs.

      These APIs are the most limited. APIs are incredibly useful in defining communication between applications and services, and this even applies when communication is within a single organization.

      A simple example of an internal API use case is a company that has two applications for selling items. One application allows customers to purchase items directly; the other allows sales personnel to process sales. Both applications need access to the inventory. The company could have both applications independently access the inventory database. However, doing so would likely lead to more difficult and inconsistent maintenance.

      So, instead, the company has an internal API for managing inventory. Both the customer-facing and sales-personnel applications can access this API to view and update inventory. Updates to each application can be made independently, as long as each adheres to the rules of the API.

      When to Use an Internal API?

      Make your API internal when you want to restrict access as much as possible. Internal APIs are designed to be private, with only applications and services within your organization having access. An internal API can even be used when different parts of an application need to communicate.

      These APIs are common within enterprise organizations. When applications scale, it helps to define APIs for managing underlying logic. Take the example above, where business logic can be developed and maintained in the customer-facing and sales-personnel applications. This can be done without concern for the impact to the underlying data storage and retrieval tasks, since those are housed in the internal API.

      Composite APIs

      Composite APIs allow for requests to be bundled or chained together, which, in turn, allows developers to receive single responses for request collections.

      These APIs are useful for reducing server load and network traffic when you expect frequent requests to multiple API endpoints. Calls get made less frequently, resulting in reductions to server processing time and the number of requests across the network.

      This makes composite APIs exceptionally effective for microservices. Often, applications built on microservices have to compile information from multiple sources. Having composite APIs that do this makes for more efficient applications.

      To give an example of a composite API in action, think of an online ordering form. When the user completes and submits the form, the application often has to register the user, check and update inventory, and send a confirmation notification. A composite API allows all of these tasks to be handled simultaneously, in a single call.

      When to Use a Composite API?

      Make use of a composite API when your application exposes endpoints that are likely to be called in groups or in quick succession. This is often the case with microservices, where requests and responses frequently need to be combined.

      This type of API can be especially useful when your
      microservice application
      needs to communicate with users’ web browsers. Here, you want to optimize network traffic to reduce load times and improve user experience. You also want to reduce your server load to make your application scalable for a larger number of users.

      What are the Different API Protocol Types?

      Every API uses a particular protocol. An API’s protocol defines the rules for how it can communicate. These rules make explicit the kinds of requests that can be made, what the API’s responses look like, and what kinds of data the API can send and receive.

      There are three main protocols used by web APIs.

      • REST. Short for Representational State Transfer, REST implements stateless APIs with uniform interfaces using HTTP. REST is actually more of a set of architectural principles for APIs than a protocol proper. You can use the
        Flask Python framework
        to build your own REST API.

      • SOAP. The Simple Object Access Protocol uses XML for requests and responses and maintains strict definitions for messages. SOAP is highly adaptable, designed to be neutral, and applicable in many contexts, not just for web APIs. It can even be used in conjunction with REST principles.

      • RPC. Simpler than both REST and SOAP, the Remote Procedural Call protocol focuses on actions taken on a server. This is in contrast to both REST and SOAP, which tend to focus on server resources. RPC works primarily on running processes. Often, RPC APIs execute scripts on the server.

      Conclusion

      This guide has walked you through the basics of APIs, explaining the different categories they fit into and the contexts they are used in. The four main types of APIs are open, partner, internal, and composite. The guide also covered the protocols web APIs use to send and receive messages. These API protocols are REST, SOAP, and RPC. You now have a strong foundation for entering into the world of web APIs. It is a wide and fast-moving world.



      Source link

      Converting Data Types in Python


      Python is a dynamically typed language, so programmers might not always consider the type of each variable they create. However, the type of a variable is often important, and it might be necessary to convert it to another data type. This guide explains how typecasting works and illustrates how to convert data types in Python. It covers several common examples, such as how to convert an integer to a string.

      Convert Data Types in Python: An Introduction

      Python, like most programming languages, supports a wide range of data types. Python is considered a strongly typed language, so each variable always has a type. The type of a variable governs the data it can represent and constrains how it can be used. Some common Python data types include integer, float, string, list, dictionary, and set. In Python, an object’s type defines its methods and the set of operations it supports. For instance, it is possible to calculate the exponent of an integer, but not of a string. For more information about Python data types, see the
      documentation for standard types
      and
      advanced types
      .

      In addition to being strongly typed, Python is also dynamically typed. This means the type of a variable is determined only at run time. The Python interpreter does not perform any type checking in advance. In addition, the type of a Python variable can change over the course of a program. Statically typed languages such as C++ do not permit this.

      It is possible to change the data type of a variable in Python through datatype conversion. Datatype conversion allows variables to be used more effectively within the program. For example, an integer can be converted into a string, allowing it to be appended to another string. There are two different methods used to convert data types in Python.

      Implicit type conversion: Python automatically performs implicit type conversion without user intervention. It can elevate a lower-order data type, such as an integer, to a higher-order type like a float. Python can initiate this conversion because any integer can be unambiguously represented as a float. There is no chance of misinterpreting the intent of this operation. Implicit conversion avoids the loss of any data and is highly convenient. However, it does not work in all cases.

      Explicit type conversion: This is also known as typecasting. An explicit conversion must be performed manually using one of Python’s built-in methods. This is necessary when the conversion is not straightforward and the intent of the operation is not clear. Some explicit type conversions can cause data loss.

      The Python type function is used to determine the type of the data. In this example, x is of type int, while y is of type float.

      x = 10
      y = 10.01
      print(type(x))
      
      <class 'int'>
      print(type(y))
      
      <class 'float'>

      Before You Begin

      Ensure Python is already installed on your machine and you understand how to launch and use the Python programming environment. To run Python on Ubuntu, use the command python3. For more information regarding how to use Python, see the
      Linode guide to Python
      .

      Converting Integers and Floats in Python

      Both floats and integers represent numerical values. A float number has a decimal point, while an integer does not. A float can more precisely represent a number, but integers make more sense when dealing with countable values. An integer can always be represented as a float, but most floats cannot be represented as integers without a loss of precision.

      This process of converting between integers and floats is relatively straightforward, because both types represent numerical data. Additional methods exist to convert integers to other formats, such as hexadecimal strings. The following examples illustrate the main methods used to convert numerical data types in Python.

      Converting Integers to Floats

      The built-in Python function float() converts an integer to a float. It accepts a single integer and returns its float equivalent in the proper format, complete with a decimal point.

      x = 10
      z = float(x)
      print("z is", z, "and is of type", type(z))
      
      z is 10.0 and is of type <class 'float'>

      Python can automatically elevate an integer to a float using implicit type conversion. Therefore, if the result of float(x) is reassigned to x, x changes type and becomes a float.

      x = 10
      x = float(x)
      print("x is", x, "and is of type", type(x))
      
      x is 10.0 and is of type <class 'float'>

      When an integer and a float are added or multiplied together, the result is a float.

      x = 10
      y = 5.2
      z = x + y
      print("z is", z, "and is of type", type(z))
      
      z is 15.2 and is of type <class 'float'>

      This occurs even if the answer can be perfectly represented as an integer. In this example, the result is 52, but it is represented as a float containing the value 52.0.

      z = x * y
      print("z is", z, "and is of type", type(z))
      
      z is 52.0 and is of type <class 'float'>

      As of Python 3, when two integers are divided, the result is a float. The numerator and denominator are both internally pre-converted to floats before the operation. This means the result is a float even if the modulus is zero.

      Note

      Python 2 returns an integer in this case.

      x = 6
      y = 3
      z = x / y
      print("z is", z, "and is of type", type(z))
      
      z is 2.0 and is of type <class 'float'>

      Note

      The closely-related hex() and oct() methods can convert an integer to its hexadecimal or octal string equivalent.

      Converting Floats to Integers

      To convert a float data type to an integer in Python, use the int() function. This function removes the fractional component of the float, also known as the
      mantissa
      , during the conversion.

      x = 50.8
      x = int(x)
      print("x is", x, "and is of type", type(x))
      
      x is 50 and is of type <class 'int'>

      This conversion leads to some data loss. The truncated portion is not recovered even if the variable is converted back to a float.

      x = float(x)
      print("x is", x, "and is of type", type(x))
      
      x is 50.0 and is of type <class 'float'>

      To convert a float to the nearest integer, use the round() function instead.

      x = 50.8
      x = round(x)
      print("x is", x, "and is of type", type(x))
      
      x is 51 and is of type <class 'int'>

      Note

      Some information is permanently lost whenever a float is converted to an integer. This can have drastic effects on the accuracy of future calculations. Ensure you understand the implications of this data loss within the context of your program before proceeding. When in doubt, create a new variable to store the converted value.

      Converting Strings in Python

      A Python string consists of an immutable sequence of Unicode characters, and is represented internally as an array. The individual characters in a string can be accessed using string indexing, which is similar to
      how list items are accessed
      . Python string indexing is zero-based, so the index [1] refers to the second character in the string. Python provides a number of built-in methods for use in string processing and manipulation.

      Integers can be converted to strings and vice versa. Strings can also be converted to complex data types including lists, sets, and tuples. For more information on strings, see the
      Python documentation
      .

      Converting Int to String in Python

      Adding an integer and a string is more complicated than adding two numbers. The integer could potentially be treated as a string, but the string could also be converted to an integer. For instance, should the operation 14 + "12" result in the string 1412 or the numerical value 26? To resolve any confusion, a Python string and integer cannot be added together or concatenated. Both entities must have the same type. Either the integer must be changed to a string, or the string must be converted to an integer. In the following example, adding a string to an integer results in an error.

      x = 12
      y = "23"
      z = x + y
      
      Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      TypeError: unsupported operand type(s) for +: 'int' and 'str'

      To convert an int to a string in Python, use the built-in function str(). When an integer is passed to the str() function, it is converted to a text representation of the number. The following example uses the str() function to perform type conversion on the integer variable x, allowing it to be concatenated to another string. The end result of the operation is another string.

      x = 12
      y = "23"
      z = str(x) + y
      print("z is", z, "and is of type", type(z))
      
      z is 1223 and is of type <class 'str'>

      This approach is frequently used to print text consisting of both strings and numbers. The numerical component is converted to a string when it is passed to the print() function.

      print(str(x) + y)
      
      1223

      The str() function can also be used to convert other data types, such as a float, to strings. This function accepts a floating point number and converts it to a string, with the decimal point and fractional component still intact.

      Convert String to Int in Python

      Mathematical operations cannot be performed on string objects. They must be converted to numbers first. Fortunately, Python’s built-in int() function is very flexible and can convert several data types to integers. This function accepts any string that can be converted to an integer, and returns an integer representation. If the string cannot represent an integer, Python throws an error. The following example demonstrates how to convert a string to an int in Python.

      x = "101"
      z = int(x)
      print("z is", z, "and is of type", type(z))
      
      z is 101 and is of type <class 'int'>

      This function can be used to add a string representation of an integer to an actual integer. This code sample converts the string to an integer, allowing the two numbers to be added together. This contrasts with the earlier example, which used str() to perform a string concatenation.

      x = 12
      y = "23"
      z = x + int(y)
      print("z is", z, "and is of type", type(z))
      
      z is 35 and is of type <class 'int'>

      When passing a string to int(), it is possible to add an optional argument indicating the base of the number. For instance, int("101", 2) indicates the binary string 101 is equivalent to 5 in decimal notation. It is not the integer 101. If a base is not provided, Python assumes it is a base-10 decimal number.

      x = "101"
      z = int(x,2)
      print("z is", z, "and is of type", type(z))
      
      z is 5 and is of type <class 'int'>

      Strings can also be converted to floats using the float() function. Python cannot automatically convert a float-like string to an integer. This function must be used if the string has a decimal point, and the string must represent a float.

      x = "10.00"
      z = float(x)
      print("z is", z, "and is of type", type(z))
      
      z is 10.0 and is of type <class 'float'>

      Note

      Do not confuse the int() function with ord(). ord() converts a character to its ASCII integer representation. This function uses the
      character to ASCII conversion table
      to determine the ASCII values.

      Converting Strings to Lists

      In Python, a list is an ordered array of objects. The items are mutable, so they can be changed. Items can be added, removed, or modified. Lists also have a large collection of built-in methods, providing advanced processing features. A list is enclosed in square brackets [ ] with commas separating the items. An example of a list is ['aa', 'bb', 'cc'].

      Lists and strings are conceptually very similar. Both are ordered sequences, and the individual items are accessed the same way. This makes it easy to convert a string to a list. The first letter in the string becomes item [0] in the list. The second letter becomes the second list item, and so on.

      Note

      The elements of a list can be strings or numbers, or even compound objects. However, strings can only contain a sequence of Unicode characters.
      Lists can also be converted to strings in Python
      , but the steps are more complicated.

      To convert a Python string to a list, use the list() function and provide the string as input. This results in a list containing the characters in the original string, formatted in list notation.

      x = "test"
      z = list(x)
      print("z is", z, "and is of type", type(z))
      
      z is ['t', 'e', 's', 't'] and is of type <class 'list'>

      Converting Strings to Tuples

      Strings are also easily converted to tuples. A Python tuple is almost the same as a list, except it is immutable. This means it cannot be changed after it is created. A tuple is always enclosed by parentheses ( ). It is sometimes a more efficient data structure for string processing because it includes more built-in functions.

      To convert a string to a tuple, use the tuple() function. The characters in the string become the ordered elements of the tuple.

      x = "test"
      z = tuple(x)
      print("z is", z, "and is of type", type(z))
      
      z is ('t', 'e', 's', 't') and is of type <class 'tuple'>

      Note

      Although it is relatively uncommon, a string can also be converted to a set. A set is an unordered collection of unique elements. Use the function set() and provide the string as a parameter.

      To learn more about Python tuples, see our guide
      An Introduction to Python Tuples
      .

      Conclusion

      Although Python is a dynamically-typed language, type conversion is still very important. Python frequently uses implicit type conversion to elevate an integer to a float, making certain operations easier. However, developers often have to use explicit type conversion, changing a type using Python’s built-in functions.

      This guide explains how to convert data types in Python. It is possible to convert a string to an integer in Python using the int() function, while the str() function converts an integer to a string. Integers can be converted to floats using float(), and floats can be changed to integers, although this can cause data loss. Other functions allow strings to be converted to array formats such as lists, tuples, and sets.

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.



      Source link

      Understanding Data Types in PHP


      The author selected Open Sourcing Mental Illness Ltd to receive a donation as part of the Write for DOnations program.

      Introduction

      In PHP, as in all programming languages, data types are used to classify one particular type of data. This is important because the specific data type you use will determine what values you can assign to it and what you can do to it (including what operations you can perform on it).

      In this tutorial, we will go over the important data types native to PHP. This is not an exhaustive investigation of data types, but will help you become familiar with what options you have available to you in PHP.

      One way to think about data types is to consider the different types of data that we use in the real world. Two different types are numbers and words. These two data types work in different ways. We would add 3 + 4 to get 7, while we would combine the words star and fish to get starfish.

      If we start evaluating different data types with one another, such as numbers and words, things start to make less sense. The following equation, for example, has no obvious answer:

      'sky' + 8

      For computers, each data type can be thought of as being quite different, like words and numbers, so we have to be careful about how we use them to assign values and how we manipulate them through operations.

      Working with Data Types

      PHP is a loosely typed language. This means, by default, if a value doesn’t match the expected data type, PHP will attempt the change the value of the wrong data type to match the expected type when possible. This is called type juggling. For example, a function that expects a string but instead receives an integer with a value of 2 will change the incoming value into the expected string type with a value of "2".

      It is possible, and encouraged, to enable strict mode on a per-file basis. This provides enforcement of data types in the code you control, while allowing the use of additional code packages that may not adhere to strict data types. Strict type is declared at the top of a file:

      <?php
      declare(strict_types=1);
      ...
      

      In strict mode, only a value corresponding exactly to the type declaration will be accepted; otherwise a TypeError will be thrown. The only exception to this rule is that an int value will pass a float type declaration.

      Numbers

      Any number you enter in PHP will be interpreted as a number. You are not required to declare what kind of data type you are entering. PHP will consider any number written without decimals as an integer (such as 138) and any number written with decimals as a float (such as 138.0).

      Integers

      Like in math, integers in computer programming are whole numbers that can be positive, negative, or 0 (…, -1, 0, 1, …). An integer can also be known as an int. As with other programming languages, you should not use commas in numbers of four digits or more, so to represent the number 1,000 in your program, write it as 1000.

      We can print out an integer in a like this:

      echo -25;
      

      Which would output:

      Output

      -25

      We can also declare a variable, which in this case is a symbol of the number we are using or manipulating, like so:

      $my_int = -25;
      echo $my_int;
      

      Which would output:

      Output

      -25

      We can do math with integers in PHP, too:

      $int_ans = 116 - 68;
      echo $int_ans;
      

      Which would output:

      Output

      48

      Integers can be used in many ways within PHP programs, and as you continue to learn more about the language you will have a lot of opportunities to work with integers and understand more about this data type.

      Floating-Point Numbers

      A floating-point number or float is a real number, meaning that it can be either a rational or an irrational number. Because of this, floating-point numbers can be numbers that can contain a fractional part, such as 9.0 or -116.42. For the purposes of thinking of a float in a PHP program, it is a number that contains a decimal point.

      Like we did with the integer, we can print out a floating-point number like this:

      echo 17.3;
      

      Which would output:

      Output

      17.3

      We can also declare a variable that stands in for a float, like so:

      $my_flt = 17.3;
      echo $my_flt;
      

      Which would output:

      Output

      17.3

      And, just like with integers, we can do math with floats in PHP, too:

      $flt_ans = 564.0 + 365.24;
      echo $flt_ans;
      

      Which would output:

      Output

      929.24

      With integers and floating-point numbers, it is important to keep in mind that 3 does not equal 3.0, because 3 refers to an integer while 3.0 refers to a float. This may or may not change the way your program functions.

      Numbers are useful when working with calculations, counting items or money, and the passage of time.

      Strings

      A string is a sequence of one or more characters that may consist of letters, numbers, or symbols. This sequence is enclosed within either single quotes '' or double quotes "":

      echo 'This is a 47 character string in single quotes.'
      echo "This is a 47 character string in double quotes."
      

      Both lines output the their value the same way:

      Output

      This is a 47 character string in single quotes. This is a 47 character string in double quotes.

      You can choose to use either single quotes or double quotes, but whichever you decide on you should be consistent within a program.

      The program “Hello, World!” demonstrates how a string can be used in computer programming, as the characters that make up the phrase Hello, World! are a string:

      echo "Hello, World!";
      

      As with other data types, we can store strings in variables and output the results:

      $hw = "Hello, World!"
      echo $hw;
      

      Either way, the output is the same:

      Output

      Hello, World!

      Like numbers, there are many operations that we can perform on strings within our programs in order to manipulate them to achieve the results we are seeking. Strings are important for communicating information to the user, and for the user to communicate information back to the program.

      Booleans

      The Boolean, or bool, data type can be one of two values, either true or false. Booleans are used to represent the truth values that are associated with the logic branch of mathematics.

      You do not use quotes when declaring a Boolean value; anything in quotes is assumed to be a string. PHP doesn’t care about case when declaring a Boolean; True, TRUE, true, and tRuE all evaluate the same. If you follow the style guide put out by the PHP-FIG, the values should be all lowercase true or false.

      Many operations in math give us answers that evaluate to either True or False:

      • greater than
        • 500 > 100 True
        • 1 > 5 False
      • less than
        • 200 < 400 True
        • 4 < 2 False
      • equal
        • 5 = 5 True
        • 500 = 400 False

      Like with any other data type, we can store a Boolean value in a variable. Unlike numbers or strings, echo cannot be used to output the value because a Boolean true value is converted to the string "1", while a Boolean false is converted to "" (an empty string). This allows “type juggling” to convert a variable back and forth between Boolean and string values. To output the value of a Boolean we have several options. To output the type along with the value of a variable, we use var_dump. To output the string representation of a variable’s value, we use var_export:

      $my_bool = 4 > 3;
      echo $my_bool;
      var_dump($my_bool);
      var_export($my_bool);
      

      Since 4 is greater than 3, we will receive the following output:

      Output

      1 bool(true) true

      The echo line converts the true Boolean to the string of 1. The var_dump outputs the variable type of bool along with the value of true. The var_export outputs the string representation of the value which is true.

      As you write more programs in PHP, you will become more familiar with how Booleans work and how different functions and operations evaluating to either True or False can change the course of the program.

      Arrays

      An array in PHP is actually an ordered map. A map is a data type that associates or “maps” values to keys. This data type has many different uses; it can be treated as an array, list, hash table, dictionary, collection, and more. Additionally, because array values in PHP can also be other arrays, multidimensional arrays are possible.

      Indexed Arrays

      In its simplest form, an array will have a numeric index or key. If you do not specify a key, PHP will automatically generate the next numeric key for you. By default, array keys are 0-indexed, which means that the first key is 0, not 1. Each element, or value, that is inside of an array can also be referred to as an item.

      An array can be defined in one of two ways. The first is using the array() language construct, which uses a comma-separated list of items. An array of integers would be defined like this:

      array(-3, -2, -1, 0, 1, 2, 3)
      

      The second and more common way to define an array is through the short array syntax using square brackets []. An array of floats would be defined like this:

      [3.14, 9.23, 111.11, 312.12, 1.05]
      

      We can also define an array of strings, and assign an array to a variable, like so:

      $sea_creatures = ['shark', 'cuttlefish', 'squid', 'mantis shrimp'];
      

      Once again, we cannot use echo to output an entire array, but we can use var_export or var_dump:

      var_export($sea_creatures);
      var_dump($sea_creatures);
      

      The output shows that the array uses numeric keys:

      Output

      array ( 0 => 'shark', 1 => 'cuttlefish', 2 => 'squid', 3 => 'mantis shrimp', ) array(4) { [0]=> string(5) "shark" [1]=> string(10) "cuttlefish" [2]=> string(5) "squid" [3]=> string(13) "mantis shrimp" }

      Because the array is 0-indexed, the var_dump shows an indexed array with numeric keys between 0 and 3. Each numeric key corresponds with a string value. The first element has a key of 0 and a value of shark. The var_dump function gives us more details about an array: there are 4 items in the array, and the value of the first item is a string with a length of 5.

      The numeric key of an indexed array may be specified when setting the value. However, the key is more commonly specified when using a named key.

      Associative Arrays

      Associative arrays are arrays with named keys. They are typically used to hold data that are related, such as the information contained in an ID. An associative array looks like this:

      ['name' => 'Sammy', 'animal' => 'shark', 'color' => 'blue', 'location' => 'ocean']
      

      Notice the double arrow operator => used to separate the strings. The words to the left of the => are the keys. The key can either be an integer or a string. The keys in the previous array are: 'name', 'animal', 'color', 'location'.

      The words to the right of the => are the values. Values can be comprised of any data type, including another array. The values in the previous array are: 'Sammy', 'shark', 'blue', 'ocean'.

      Like the indexed array, let’s store the associative array inside a variable, and output the details:

      $sammy = ['name' => 'Sammy', 'animal' => 'shark', 'color' => 'blue', 'location' => 'ocean'];
      var_dump($sammy);
      

      The results will describe this array as having 4 elements. The string for each key is given, but only the value specifies the type string with a character count:

      Output

      array(4) { ["name"]=> string(5) "Sammy" ["animal"]=> string(5) "shark" ["color"]=> string(4) "blue" ["location"]=> string(5) "ocean" }

      Associative arrays allow us to more precisely access a single element. If we want to isolate Sammy’s color, we can do so by adding square brackets containing the name of the key after the array variable:

      echo $sammy['color'];
      

      The resulting output:

      Output

      blue

      As arrays offer key-value mapping for storing data, they can be important elements in your PHP program.

      Constants

      While a constant is not actually a separate data type, it does work differently than other data types. As the name implies, constants are variables which are declared once, after which they do not change throughout your application. The name of a constant should always be uppercase and does not start with a dollar sign. A constant can be declared using either the define function or the const keyword:

      define('MIN_VALUE', 1);
      const MAX_VALUE = 10;
      

      The define function takes two parameters: the first is a string containing the name of the constant, and the second is the value to assign. This could be any of the data type values explained earlier. The const keyword allows the constant to be assigned a value in the same manner as other data types, using the single equal sign. A constant can be used within your application in the same way as other variables, except they will not be interpreted within a double quoted string:

      echo "The value must be between MIN_VALUE and MAX_VALUE";
      echo "The value must be between ".MIN_VALUE." and ".MAX_VALUE;
      

      Because the constants are not interpreted, the output of these lines is different:

      Output

      The value must be between MIN_VALUE and MAX_VALUE The value must be between 1 and 10

      Conclusion

      At this point, you should have a better understanding of some of the major data types that are available for you to use in PHP. Each of these data types will become important as you develop programming projects in the PHP language.



      Source link