In this article, we'll look at how we can convert the following to an array in PHP:
- Scalar types (i.e. boolean, integer, float and string)
null
- Resource
- Object
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.
- Converting
null
to 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 settype
Behind the scenes, settype()
works the same as type casting. The thing to remember about settype()
is that it returns boolean true
or 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
Using settype($arr, 'array')
on an array has no effect.
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.