In this article, we'll look at ways to convert any of the following to an array in PHP:
- Scalar types (i.e. boolean, integer, float and string)
Important stuff to remember about converting to an array:
- Converting scalars and resource to an array results in an array with a single element with index zero having the value of the scalar/resource which was converted.
nullto an array results in an empty array.
- Converting an object to an array results in an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions:
- Integer properties are unaccessible;
- Private variables have the class name prepended to the variable name;
- Protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behavior.
Casting To An Array
You could simply cast to an array like so:
$var = 'hello world!'; $arr = ['hello world!']; echo ((array)$var === (array)$arr); // output: true
Casting an array to an array has no effect.
Converting To An Array Using Ternary Operator
$var = 'hello world!'; $var = (is_array($var)) ? $var : [$var]; $arr = ['hello world!']; $arr = (is_array($arr)) ? $arr : [$arr]; echo ($var === $arr); // output: true
Converting A Variable To An Array Using
Behind the scenes,
settype() works the same as type casting. The thing to remember about
settype() is that it returns boolean
false and takes a variable as the first argument. For example:
$var = 'hello world!'; $arr = ['hello world!']; settype($var, 'array'); settype($arr, 'array'); echo ($var === $arr); // output: true
settype($arr, 'array') on an array has no effect.
If there's anything you would like to add, please let us know in the comments section.