You get a bonus - 1 coin for daily activity. Now you have 1 coin

Manipulations with PHP data types

Lecture




Cast

Type casting in PHP works the same way as in C: the name of the required type is written in parentheses in front of the variable. Example:

<?php
$foo = 10; // $foo это целое число
$bar = (boolean) $foo; // $bar это булев тип
?>

The following type conversions are allowed:

  • (int), (integer) - coercion to integer

  • (bool), (boolean) - coercion to boolean type

  • (float), (double), (real) - reduction to a floating-point number (float)

  • (string) - cast to string

  • (array) - cast to array

  • (object) - cast to object

Note that inside the brackets, spaces and tabs are allowed, so the following is equivalent in its effect:

<?php
$foo = (int) $bar;
$foo = ( int ) $bar;
?>

Tip: instead of casting a variable to a string, you can enclose it in double quotes.

<?php
$foo = 10; // $foo это целое число
$str = "$foo"; // $str это строка
$fst = (string) $foo; // $fst это также строка

// Это напечатает "они одинаковы"
if ($fst === $str) {
echo "они одинаковы";
}
?>

Conversion to Boolean Type (Binary Data)

For an undoubted conversion of a value into a boolean type, use a type cast (bool) or (boolean) . However, in most cases you do not need to use a cast, since the value will be automatically converted if the operator, function, or control construct requires a boolean argument.

When converting to a boolean type, the following values ​​are considered FALSE :

  • Boolean itself FALSE

  • integer 0 (zero)

  • floating point number 0.0 (zero)

  • empty line and string "0"

  • array with zero elements

  • object with zero member variables

  • special type NULL (including unset variables)

All other values ​​are treated as TRUE (including any resource).

Warning: -1 is considered TRUE , like any non-zero (negative or positive) number!

Conversion examples:

<?php
var_dump((bool) ""); // bool(false)
var_dump((bool) 1); // bool(true)
var_dump((bool) -2); // bool(true)
var_dump((bool) "foo"); // bool(true)
var_dump((bool) 2.3e5); // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array()); // bool(false)
var_dump((bool) "false"); // bool(true)
?>

See also: settype () and gettype ()

Conversion to Integer (Integers)

To undoubtedly convert a value to an integer, use a cast (int) or (integer) . However, in most cases you do not need to use a cast, since the value will be automatically converted if an operator, function, or control construct requires an integer argument. You can also convert a value to an integer using the intval () function.

Convert from Boolean Type

FALSE is converted to 0 (zero), and TRUE is converted to 1 (one).

Conversion from Float type

When converting from a floating point number to an integer, the number will be rounded to zero .

If the floating-point number exceeds the limits of the integer (as a rule, it is +/- 2.15e + 9 = 2 ^ 31 ), the result will be undefined, since the integer does not have sufficient accuracy to return the correct result. In this case, neither a warning nor even a comment will be displayed.

Attention! Never give an unknown fraction to a whole, as it can sometimes give unexpected results, for example:

<?php
echo (int) ( (0.1+0.7) * 10 ); // выводит 7!
?>

See more about this issue: a warning about the accuracy of floating point numbers.

Convert from String

See Converting Strings to Numbers

Conversions from other types

For other types, the conversion behavior to integer is undefined. Currently, the behavior is the same as if the value was first converted to a boolean type. However, do not rely on this behavior, as it may change without warning.

Conversion to Float type (floating point numbers)

For information on when and how strings are converted to floating point numbers, see here . For values ​​of other types, the conversion will be the same as if the value was first converted to an integer, and then to a floating point number. For more information, see Conversion to Integer.

Conversion to String Type (Strings)

You can convert a value to a string using the cast (string) or the strval () function. In expressions where a string is needed, the conversion occurs automatically. This happens when you use the echo () or print () function, or when you compare the value of a variable with a string. Familiarizing yourself with the "Data Types" and "Type Manipulation" sections allows you to better understand the essence. See also settype () .

A boolean value is converted to the string "1" , and the value FALSE is represented as "" (empty string). In this way, you can convert values ​​in both directions - from the boolean type to the string type and vice versa.

An integer or floating point number ( float ) is converted to a string represented by a number consisting of its digits (including an exponent for floating point numbers).

Arrays are always converted to the string "Array" , so you cannot display the contents of an array ( array ) using echo () or print () to find out what it contains. To view one element, you need to do something like echo $ arr ['foo'] . See below for tips on how to display / view all content.

Objects are always converted to the string "Object" . If you want to display the value of a member variable of an object ( object ) for debugging purposes, read the following paragraphs. If you want to get the class name of the desired object, use get_class () .

Resources are always converted to strings with the structure "Resource id # 1" , where 1 is the unique resource number assigned to PHP at run time. If you want to get a resource type, use get_resource_type () .

NULL is always converted to an empty string.

Outputting arrays, objects, or resources does not provide you with any useful information about the values ​​themselves. A more suitable way to output values ​​for debugging is to use the print_r () and var_dump () functions.

You can also convert PHP values ​​to strings for persistent storage. This method is called serialization and can be performed using the serialize () function. In addition, if your PHP installation has support for WDDX, you can serialize PHP values ​​into XML structures.

Conversion to Array type (arrays)

For any of the types: integer , float , string , boolean, and resource , if you convert the value into an array, you get an array with one element (with index 0), which is the scalar value that you started with.

If you convert an object ( object ) into an array, you will receive the properties (member variables) of this object as array elements. The keys are the names of the member variables.

If you convert a null value to an array, you get an empty array.

Conversion to Object Type

If an object is converted to an object, it does not change. If a value of any other type is converted to an object, a new instance of the built-in class stdClass is created . If the value was empty, the new instance will also be empty. For any other value, it will be contained in the scalar member variable :

<?php
$obj = (object) 'ciao';
echo $obj->scalar; // выведет 'ciao'
?>

See also: Classes and Objects

Conversion to Resource Type

Since a resource type contains special pointers to open files, connections to a database, an image area, and the like, you cannot convert any value to a resource.

Convert strings to numbers

If the string is recognized as a numeric value, the resulting value and type is determined as shown below.

The string will be recognized as a float if it contains any of the characters '.', 'E', or 'E'. Otherwise, it will be defined as an integer.

The value is determined by the beginning of the string. If the string starts with a valid numeric value, this value will be used. Otherwise, the value will be 0 (zero). The correct numeric value is one or more digits (which may contain a decimal point), optionally preceded by a sign, followed by an optional exponent. The exponent is 'e' or 'E' followed by one or more digits.

<?php
$foo = 1 + "10.5"; // $foo это float (11.5)
$foo = 1 + "-1.3e3"; // $foo это float (-1299)
$foo = 1 + "bob-1.3e3"; // $foo это integer (1)
$foo = 1 + "bob3"; // $foo это integer (1)
$foo = 1 + "10 Small Pigs"; // $foo это integer (11)
$foo = 4 + "10.2 Little Piggies"; // $foo это float (14.2)
$foo = "10.0 pigs " + 1; // $foo это float (11)
$foo = "10.0 pigs " + 1.0; // $foo это float (11)
?>

For more information about this conversion, see the section on strtod (3) Unix documentation.

If you want to test any of the examples in this section, you can copy and paste it and the following line to see what happens:

<?php
echo "\$foo==$foo; тип: " . gettype ($foo) . "<br />\n";
?>

Do not expect to receive a character code by converting it to an integer (as you could do, for example, in C). To convert characters to their codes and back, use the functions ord () and chr () .

created: 2016-01-25
updated: 2021-03-13
132459



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)