Php data types
Types in PHP are a representation of data because it does not require variables to declare their type, because all types are converted automatically
Type boolean
The Boolean type simply distinguishes between two states, a success or enabled state, true value, true, and a failure or deactivated state, false value, false
Both states are not case sensitive
Typically, the result of operators that return a Boolean value are passed to a control structure
Numeric types
The numeric types can be divided into real and integer
Type integer numeric
- Integer
integer base 10
Both positive and negative
- Hexadecimal
integer base 16
Placed before the base number 16 0x or 0X
- Octal
integer base 8
We place a zero before the number in octal
- Binary
integer base 2
Placed before the base number 2 0b or 0B
Formally, the structure of integer literals is:
decimal : [1-9][0-9]* | 0
hexadecimal : 0[xX][0-9a-fA-F]+
octal : 0[0-7]+
binary : 0b[01]+
integer : [+-]?decimal | [+-]?hexadecimal | [+-]?octal | [+-]?binary
Numeric type real
The actual is made up of a whole part and the other fractional separated by a point of the previous
The fractional part can be composed by an indicator of exponent E or E followed by an integer that indicates the value of the exponent
Formally, the structure of the actual type literals is:
LNUM : [0-9]+
DNUM : ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM : [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM})
- Float
is a floating-point numerical value
Both positive and negative
Its size depends on the platform, although its value can be a maximum of approximately 1.8e308, with an accuracy close to 14 decimal digits (IEEE 64 bit format)
Additionally, rational numbers whose base 10 representation is equal to that used as a floating-point number, such as 0.1 or 0.7, do not have an exact representation as base 2 floating-point numbers, which is the internally employed basis, regardless of the mantissa size
Therefore, they cannot be converted to binary without a small loss of precision
Being able to result in precision errors such as floor( (0.1 + 0.7) * 10); normally it would return 8, however, it would return 7, since in its internal representation it will be 7.9999999999999991118...
Therefore, it is not recommended to trust results with floating-point numbers and not to use the comparison of floating point numbers directly
If you need more precision, use the mathematical functions of arbitrary precision and the functions of gmp
- Double
is equivalent to Float and does not provide substantial differences
In other languages it has double precision, but in PHP it has been maintained for historical reasons and it is advisable to better use the functions that work with Float
- NaN
Some numerical operations may result in a value represented by the NAN constant
This result represents an undefined or unrepresentable value using floating point calculations
Any comparison, whether strict or not, of this value with any other value, including itself, except for TRUE, will result in FALSE
Since it represents any number of different values, it should not be compared with other values, including itself; instead it should be checked using the function is_nan()
Type string
A string is a string of characters delimited by quotation marks
Where each character is a byte
This means that PHP only supports a set of 256 characters, hence it does not offer native support for Unicode
A string can only contain up to 2 GB in size (2147483647 bytes maximum)
A string literal can be specified in four different ways:
- single quote
are specified between the characters ‘ opening and ‘ closing
To specify a single literal quote, you must escape with a backslash (\). To specify a literal backslash, duplicate (\\)
All other instances of backslashes will be treated as a literal backslash: this means that other escape sequences that could be used, such as \r or \n, will be displayed literally as specified, instead of having any other special meaning
Keep in mind that variables and escape statements for special characters will not be expanded when they are included in a string in single quotes
- double quotes
are specified between the characters " opening and " closing
The most important feature of double string quotation marks is the fact that variable names are expanded
PHP will interpret the following escape sequences as special characters:
Code |
Description |
\n |
line feed (LF or 0x0A (10) in ASCII) |
\r |
carriage return (CR or 0x0D (13) in ASCII) |
\t |
horizontal tab (HT or 0x09 (9) in ASCII) |
\v |
vertical tabulator (VT or 0x0B (11) in ASCII) (since PHP 5.2.5) |
\e |
escape (ESC or 0x1B (27) in ASCII) (since PHP 5.4.4) |
\f |
page feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5) |
\\ |
backslash |
\$ |
dollar sign |
\" |
double quotes |
\[0-7]{1,3} |
the sequence of characters that matches the regular expression is a character in octal notation, which silently overflows to fit into a byte ("\400" === "\000") |
\x[0-9A-Fa-f]{1,2} |
the sequence of characters that matches the regular expression is a character in hexadecimal notation |
\u{[0-9A-Fa-f]+} |
the character sequence that matches the regular expression is a Unicode code point, which will be printed to the string as that UTF-8 representation of the code point (added in PHP 7) |
As in the simple quotation mark of a string, escaping any other character can result in the backslash also being displayed
Prior to PHP 5.1.1, the backslash of the \{$var}
- heredoc syntax
are specified by the characters <<< followed by the operator EOT and ends with the EOT operator followed by the ; closing
The closing identifier must start in the first column of the new line
Also, the identifier must follow the same naming rules as tags in PHP: it must contain only alphanumeric characters and underscores, and must start with an alphabetic character or underscore
It is very important to note that the line with the closing identifier must not contain any other characters except the semicolon
The identifier must not be indented, and there should be no space or tab before or after the semicolon
The first character before the closing identifier must be a line break defined by the local operating system
\n UNIX systems, including Mac OS X
In addition, the closing delimiter must also be followed by the newline
If this rule is broken and the closing identifier is not clean, will not be considered as a closing identifier, so PHP will continue to look for one
If no appropriate closing identifier is found before the end of the file, a parsing error will occur on the last line
You cannot use Heredoc to initialize the properties of a class
Since PHP 5.3, this limitation is valid only for an heredoc that contains variables, as it is possible to initialize static variables and class properties/constants
In that version we also introduced the possibility of quoting the opening identifier in Heredoc
- nowdoc syntax (since PHP 5.3)
is to strings with single quotes the same as Heredoc is to strings with double quotes
A nowdoc is specified similarly to a heredoc, but no analysis is performed within the nowdoc
The construction is ideal for embedding PHP code or large pieces of text without having to escape them
Share some common features with construction SGML, where a block of text is declared that is not parsed
A nowdoc is identified by the same sequence used for heredoc, <<<, but the identifier that follows it is delimited with single quotation marks
All rules for heredoc identifiers also apply to nowdoc identifiers, especially those that refer to the use of the closing identifier
Variable analysis
When a string is specified by double quotation marks or by heredoc, variables within that string will be parsed
There are two types of syntax:
- simple
is the most employed and practical
Provides a way to embed a variable, an array value, or a property of an object within a string with minimal effort
- complex
can be recognized by the keys that delimit the expression
Simple syntax
If a dollar sign ($) is found, the analyzer will take the largest number of symbols to form a valid variable name
Delimiting the variable name with braces allows you to explicitly specify the end of the name
Similarly, you can analyze the index of an array or the property of an object
With array indices, the closing bracket (]) marks the end of the index
The same rule can be applied to object properties and simple variables
Complex syntax
Allows the use of complex expressions
Any scalar variable, array element, or object property with a representation of type string can be included through this syntax
You simply type the expression the same way it would appear outside the string, delimiting it with { and }
Given that { cannot be escaped, this syntax will be recognized only when the $ immediately follow the {
Use {\$ to get a {$ literal
Some examples to make it clearer:
With this syntax, it is also possible to access the properties of a class by using variables within a string
Functions, method calls, static class variables, and class constants within {$} work from PHP 5
However, the accessed value can be interpreted as the variable name in the scope in which the string is defined
The use of simple keys ({}) will not be used to access the value returned by functions or methods, or the values of static class constants or class variables
Arrays
An array in PHP is actually an ordered map
A map is a type of data that associates values with keys
This type is optimized for several different uses; it can be used as an array, list (vector), associative table (hash table – an implementation of a map), dictionary, collection, stack, queue, etc
Since the values of an array can be other arrays, multidimensional trees and arrays are also possible
The following syntax is used to create an array:
Where we have the function array() which serves as a constructandr and takes as parameters key/value pairs separated by commas and joined with the symbols =>
The comma after the last element of the array is optional, and can be omitted
Since with PHP 5.4 you can also use the short array syntax, which replaces the function array() with []
The key can be an integer or a string
In addition, the keys must comply with:
-
A strings containing a valid integer will be mourned to the integer type
The key "8" will actually be stored as 8
"08" not be converted as it's not a valid decimal integer number
-
A float will be forced to integer, which means that the decimal part be removed
The key 8.7 actually be stored as 8
- A Boolean be forced to integer also, namely, the true key will actually be stored as 1 and false as the key 0
- Un null será forzado a string vacío, es decir, la clave null en realidad será almacenada como ""
- Arrays and objects can not be used as key
If we do, we will place a warning: Illegal offset type
- If several elements in the declaration of the array using the same key, only the latter will be used, the others being overwritten
The key is optional and if not specified, PHP will use the increase in the key rate previously used integer greater
You can specify the key only to some elements and exclude others:
Array elements can be accessed using the syntax array[key]
Note Both brackets as the keys can be used interchangeably to access array elements ($array[42] and $array{42} will have the same result in the previous example)
Since PHP 5.4 is possible to refer to the array of the result of a call to a function or method directly
In previous versions it was only possible using a temporary variable
Since PHP 5.5 it is possible to directly reference an element of an array literal
Note Trying to access a key part of an array that is not defined is the same as accessing any other undefined variable: an error message will be issued level E_NOTICE, and the result will be NULL
An existing array can be modified by explicitly setting values in it
This is done by assigning values to the array, specifying the key in brackets
This can also be omitted, resulting in an empty pair of brackets ([])
If $arr does not yet exist, it is created, this being also an alternative way to create an array
However, this practice is discouraged because if $arr already contains a value (a string of a request variable), this will be in place and [] can really mean the access operator strings
It is always better to initialize variables through direct allocation
To change a certain value must be assigned a new value to that element using its key
To remove a key/value pair, call the function unset()
Iterables
A Iterable is a pseudotype introduced in PHP 7.1
Accepts any array or object that implements the interface Traversable
These two types are crossed with foreach and can be used to yield from within a generator
Iterable may be used to indicate that a function requires a set of values, but no matter the form of the whole and it will be used with foreach
If a value is not an array or an instance of Traversable, it will launch a TypeError
Parameters declared as iterable be used NULL or an array as the default
Objects
Objects consist of a set of values, properties, and a set of methods applied to those values
It is these methods that allow us to modify the state of that object, that is, the value of its properties
Let's create a academic sample object where you have the properties: Name, Surname, Age and Identity card
The instance of the object we'll create using the new operator as follows:
You can initialize all variables to have the kind we want, we will use the class constructor passing the arguments we need
From PHP 7 we can also specify the type of the argument
By keyword $this we can reference to the current object
The properties of an object can be described by other objects
The definition of methods associated with an object can be specified in the object definition
For example, for the university object we define a function that shows the student's first name, age, last name, id, and middle grades
To access the properties or methods will use the operator ->
Resources
A resource type is a special value variable, which contains a reference to an external resource
Resources are created and used by special functions
You can be obtained by the resource type function get_resource_type()
Thanks to the reference-counting system introduced with PHP 4's Zend Engine, a resource that is no longer referenced is automatically detected and is released by the garbage collector
For this reason, rarely you need to free the memory manually
Note Persistent links to databases are an exception to this rule
They are not destroyed by the garbage collector to being persistent connections
Null value
PHP variables can be assigned a value indicating the empty value, this value is the value NULL
A variable is considered NULL if:
- has been assigned the constant NULL
- has not yet been assigned a value
- has been destroyed function unset()
The constant NULL is insensitive to case sensitive
The conversion of data types
First of all, remember that PHP does not need type declaration
The contents of the variable will be converted automatically in the course of the programme according to its use
The type conversion scheme is based on the following principle: the associated type corresponds to that of the left operand
This is because the evaluation is done from left to right
The first expression will convert the variable $a_number in a string of characters because the operand on the left $a_string is a string of characters
This expression concatenates the two character strings and the result of x is: "742"
In contrast, the second expression converts the string $a_string in a numerical value because the operand on the left $a_number, is a number
This second expression sums the two numbers and the result of and is: 49
Type conversion cannot be done in all possible cases: certain character strings cannot be converted to number
Such conversions fail with an error
The behavior of automatic array conversion is currently undefined
Because PHP supports string indexing using offsets using the same syntax used in array indexing, the following examples are valid for all PHP versions:
Casting
Casting in PHP works the same way as in C, where the name of the desired type is enclosed in parentheses before the variable you want to force
Type |
Forced |
(int), (integer) |
integer |
(bool), (boolean) |
boolean |
(float), (double), (real) |
float |
(string) |
string |
(array) |
array |
(object) |
object |
(unset) |
NULL (added in PHP 5) |
(binary) y prefijo b |
binary string (added in PHP 5.2.1) |
Tabs and spaces are allowed within parentheses, so the following examples are functionally equivalent:
Example of literal snapping of strings and variables to binary strings
Double quotation marks allow you to avoid forcing a variable to string, because the result is equivalent
Converting to boolean
To explicitly convert a value to the boolean type, use casting (bool) or (boolean)
However, in most cases it is unnecessary, because a value will be converted automatically if an operator, function, or control structure requires an argument of type boolean
A value can also be converted to the boolean type using the function boolval()
When converting to boolean, the following values are considered FALSE:
- the boolean FALSE
- the integer 0 (zero)
- the float 0.0 (zero)
- the string value empty, and the string "0"
- an array with zero elements
- an Object with zero member variables (PHP 4 only)
- special type NULL (including variables not set)
- SimpleXML objects created from empty tags
Any other value is considered TRUE (including a resource variable)
Note: -1 is considered TRUE, like any other non zero (whether positive or negative)
Converting to integer
To explicitly convert a value to the integer type, use casting (int) or (integer)
However, in most cases it is unnecessary, since a value will be automatically converted if an operator, function or control structure requires an argument of type integer
A value can also be converted to the integer type by function intval()
If a resource is converted to integer, the result will be the number one resource assigned to the resource by PHP at runtime
From Booleans
FALSE will produce 0 (zero), and TRUE will produce 1 (one)
From floating point numbers
When a float is converted to an integer, the number be rounded towards zero
If the value of type float is below the limit of an integer (usually +/- 2.15e+9 = 2^31 on 32 bit platforms and +/- 9.22e+18 = 2^63 64 bit platforms other than Windows), the result is undefined, because float does not have sufficient precision to deliver the result as an exact integer
No warning is displayed, not even a warning when this happens
Note From PHP 7, instead of being indefinite and platform dependent, NaN and Infinity always be zero forcing type to integer
Note You should never turn an unknown fraction to integer, as sometimes can lead to unexpected results
From strings
If the string does not contain any of the '.', 'E', or 'E', and the numerical value is within the bounds of the integer type (as defined by PHP_INT_MAX), the string is evaluated as an integer
In all other cases it will be evaluated as a float
The value is given by the initial portion of the string
If the string starts with valid numeric data, this will be the value used
Otherwise, the value is 0 (zero)
A valid numeric data is an optional sign, followed by one or more digits
Do not wait for the code of one character by converting it to integer, as in C
Use functions ord() and chr() to convert characters to their ASCII code
From other types
The behavior of converting to integer is undefined other
Do not rely on any observed behavior, as it can change without notice
Converting to floating point number
To explicitly convert a value to the float type, use the casting (float) or (double) or (real)
However, in most cases it is unnecessary, because a value will be converted automatically if an operator, function, or control structure requires an argument of type float
A value can also be converted to the type float by function floatval()
From strings
If the string does not contain any of the '.', 'E', or 'E', and the numerical value is within the bounds of the integer type (as defined by PHP_INT_MAX), the string is evaluated as an integer
In all other cases it will be evaluated as a float
The value is given by the initial portion of the string
If the string starts with valid numeric data, this will be the value used
Otherwise, the value is 0 (zero)
Valid numeric data is an optional sign followed by one or more digits (optionally may contain a decimal point), followed by an optional exponent
The exponent is an 'e' or 'E' followed by one or more digits
From other types
The conversion is the same as if the value had been converted first to integer and then to float
Starting with PHP 5, a warning is generated if you try to convert an object to float
Converting to String
To explicitly convert a value to the string type, use the casting (string)
However, in most cases it is unnecessary, since a value will be automatically converted if an operator, function or control structure requires an argument of type string
A value can also be converted to the string type by function strval()
There is also an automatic conversion when used display functions echo or print
From Booleans
The value TRUE of the type boolean is converted to the string "1"
The value FALSE of the type boolean is converted to the string "" (the empty string)
This allows the conversion in both directions between the values boolean and string types
From numbers
An integer or float is converted to a string that represents the number textually (including the exponent part for float)
Floating point numbers can be converted using exponential notation (for example 4.1E+6)
Note The character for the decimal point is defined in the script locale variable (category LC_NUMERIC). See the function setlocale()
From arrays
Arrays are always converted to the string " Array"
For this reason, echo and print can't by themselves display the contents of an array
To view a single item individually, use a construct such as echo $arr[‘foo’]
You can use the function print_r to perform the conversion and visualize the contents of the entire array
From object
Objects from PHP 4 are always converted to string "Object"
To get the class name of an object, use the function get_class()
Since PHP 5, you can use the method __toString when relevant
You can use the functions print_r or var_dump() to see more effective means of inspecting the content of these types
From resource
A resource is always converted to string with the structure "Resource id #1", where 1 is the resource number assigned to the resource by PHP during execution
Although it should not be dependent on the exact structure, because it is subject to changes during execution, it will always be unique for a given resource within the lifetime of that running script (that is, a web request or CLI process), so it won't be reused
To get the type of a resource, use the function get_resource_type()
You can use the functions print_r or var_dump() to see more effective means of inspecting the content of these types
From NULL
NULL is always converted to an empty string ""
From other types
Most PHP values can be converted to a string for permanent storage
This method is called serialization, and is performed by the function serialize()
Because the PHP engine was built with support for WDDX, PHP values can also be serialized as well formed XML text
Converting to array
From object
If you convert an object to an array, the result is an array whose elements are the properties of the object
Keys are the names of member variables, with some notable exceptions: private variables have the class name at the beginning of the variable name; protected variables have a '*' character at the beginning of the variable name
These values added at startup have null bytes on the sides
This can result in some unexpected behaviors:
From NULL
If you convert a value NULL to array, you get an empty array
From other types
For any of the types: integer, float, string, boolean, and resource, converting a value to an array results in an array with a single element, with index 0, and the scalar value that was converted
In other words, (array) $scalarValue is exactly the same as array($scalarValue)
Converting to object
If an object becomes an object, it is not modified
From other types
If a value of any other type becomes an object, a new instance of the built-in stdClass class is created
If the value is NULL, the new instance will be empty
An array becomes an object with the properties named as keys and the corresponding values, with the exception of the numeric keys, which will be inaccessible unless they are traversed
Converting to resource
Since the resource variables contain special managers to open files, connections to databases, graphic areas for images and the like, the conversion to resource type is meaningless
Conversting to NULL
Note This feature has been declared deprecated as of PHP 7.2 and its use is totally discouraged
Converting a variable to null using (unset) $var will not delete the variable or destroy its value
It will only return one value NULL