Tuesday, November 30, 2021

PHP Type Casting: A Complete Guide

PHP Type Casting: A Complete Guide

When you are writing a program, you will need to create and manipulate multiple variables. These variables might store the same or different types of data. For example, some of them could have an integer value while others could be a string or float.

Different programming languages have their own set of rules for defining and declaring variables. A language like C++ needs you to specify the type of variable before you can start using it and won't implicitly convert it to some other type. PHP, on the other hand, has somewhat relaxed rules around types. You don't have to specify the type of value that you will store in a variable beforehand. It also allows you to store a different kind of value in the same variable without any explicit type conversion at a later point.

PHP does this type conversion for you automatically based on the context in which a variable is used. In this tutorial, you will learn what rules are followed for this type conversion and how you can do type casting explicitly whenever needed.

Allowed Type Casts in PHP

You can cast one type of values into another by adding your desired type in parenthesis before the variable that you want to cast.

There are six main type casts allowed in PHP. These are listed below:

  • cast to int by using (int) or (integer)
  • cast to bool using (bool) or (boolean)
  • cast to float using (float), (double) or (real)
  • cast to string using (string)
  • cast to array using (array)
  • cast to object using (object)

Two additional type casts are binary casting and null casting. In previous versions of PHP, you could cast a variable to NULL by prefixing it with (unset). However, this has been deprecated since PHP 7.2.0 and removed since PHP 8.0.0. The binary casting exists for forward support and for now it behaves the same as (string). However, things may change in the future so I wouldn't advice you to rely on this behavior.

Casting Values to Boolean

A boolean can only have two possible values. It will either be true or false. Boolean values are generally passed to control structures to modify the flow of a program. You can cast any variable to a boolean by prefixing it with (bool) or (boolean). However, this isn't always necessary because PHP can determine from the context if you want a value to be evaluated as a boolean.

The boolean false itself naturally evaluates to false. The integer value 0, float values 0.0 and -0.0, an empty string as well as the string "0", an array with zero elements and the type NULL are all considered false when converting a value to boolean. Additionally, SimpleXML objects that are created from empty elements with no attributes also evaluate to false.

Every other value will evaluate to true. This also includes the string "false" and integer values like -1.

Initial Value Cast to Boolean
false false
"false" true
0 false
"0" false
"zero" true
"" false
-1 true
"empty" true
"null" true
array() false

As you can see, only the empty string and the string "0" evaluate to false, every other string like "zero", "empty", "false" or "null" evaluates to true.

Casting Values to Integers

You can cast any variable into an integer by prefixing it with (int) or (integer). Another way to convert a value to integer is to use the intval() function. Usually, you won't need to explicitly make these conversions because PHP will look at the context in which the variable is being used and convert it automatically if needed.

There are certain rules about integer conversion that you should keep in mind to avoid any unexpected surprises.

  1. A boolean false becomes 0 and a boolean true becomes 1.
  2. Floating point numbers will always be rounded towards zero.
  3. NaN and Infinity always evaluate to zero when cast to int.
  4. A string which is either fully numeric or leading numeric is converted to corresponding numeric values. All other strings evaluate to zero.
  5. The value null is always converted to zero.
Initial Value Cast to Int
false 0
true 1
"-1" -1
"null" 0
"twenty" 0
"20.855 apples" 20
"1.2e8" 120000000
12.7 12
-5.9 -5

Two things to observe here are the conversion of string "twenty" to 0 and the conversion of "20.855 apples" to 20. In this second string, the decimal part was dropped because we are casting to integers.

Casting Values to Floats

Floats or floating point numbers are also known as doubles or real numbers. Unlike int which can only store integers and not decimals, a float can store all types of numbers. You can cast any variable into a float by adding (float), (double) or (real) before it.

There are only two rules that you need to remember about casting of values to floats.

  1. A numeric or leading numeric string will resolve to corresponding float value. All other strings will be evaluated to zero.
  2. All other types of values are first converted to integers and then to a float.
Initial Value Cast to Float
false 0
true 1
"-1" -1
"null" 0
"twenty" 0
"20.855 apples" 20.855
"1.2e8" 12000000

This time the entire number 20.855 was retained because the string is being cast into a float and floats  can represent the decimal part of a number.

Casting Values to Strings

You can convert any value to a string either by adding (string) before it or by calling the strval() function. PHP also does this conversion automatically for expressions which expect a string. This includes things like calling echo or comparing a variable to a string.

Conventions followed by PHP when converting anything to a string are listed below.

  1. A false boolean value becomes an empty string and a true value becomes the string "1".
  2. Integers and floats are converted to textual representation of those numbers.
  3. All arrays are converted to the string "Array".
  4. The value NULL is always converted to an empty string.
  5. Objects are converted to a string with the help of the __toString() magic method.
  6. Resources are converted to strings based on the format "Resource id #X" where X is a number like 1,2,3 etc. assigned to the resource by PHP at runtime.

As you can see, converting an array, object or resource to a string does not yield any useful results. You should consider using functions like var_dump() if you want to see the data stored inside these types of values.

Initial Value Cast to String
false ""
true "1"
"false" "false"
0 "0"
1.24984e8 "124984000"
-38 "-38"
["Apple", "Monkey", 38] "Array"
[] "Array"
null ""

Casting Values to Arrays

An array is used to store a bunch of elements to be accessed later. Arrays can contain zero, one or more elements. Therefore, converting values of type integer, float, string, bool and resource creates an array with a single element. The element can be accessed at the index zero within the new array.

Casting a NULL into an array will give you an empty array.

Initial Value Cast to Array
false [false]
true [true]
"false" [false]
"apple" ["apple"]
12984000
[12984000]
-38 [-38]
null
[]

Casting an Object to an Array

Conversion of objects to arrays is a bit more complicated. The elements of the final array are the object's properties. The keys of those elements are derived from the member variable names based on the following rules.

  1. Class names are prepended to private variable names. A NUL byte is appended on both sides of the prefix.
  2. An asterisk (*) is prepended to protected variable names. A NUL byte is appended on both sides of the prefix in this case as well.
  3. Public variable names are directly used as keys.

As you can see in the above example, the NUL byte is not evident when you simply use var_dump() but it is actually present inside the arrays' keys.

Casting Values to NULL, Resources or Objects

In earlier versions of PHP, you could cast a value to NULL by prefixing it with (unset). However, this has been removed from PHP 8.0.0.

Resource variables are used to store a reference to some external resource. These can be opened files, database connections or images etc. Resources provide us a way to access external objects internally. Therefore, it doesn't make any sense to convert arrays, string or floats in PHP to resources.

Casting an integer, float, array or string into an object results in creation of a new instance of the built-in PHP class stdClass. A value of null results in an empty new instance.

Conversion of an array into an object is done with keys considered as property names and their corresponding values as the value of those properties.

All other types of values are cast into an object with a member variable named scalar that stores the value.

Final Thoughts

In this tutorial, we have tried to cover all the basics of type casting in PHP. We began the tutorial by mentioning that PHP can automatically handle type conversion in most situations where it is required. Then we listed different types that you are allowed to cast values into in PHP. However, PHP follows certain rules when doing all this type casting. Keep them in mind and you will avoid some unexpected surprises.


No comments:

Post a Comment