How To Convert A Variable Into An Array In PHP?

Learn about the different ways you can quickly and easily convert a variable into an array in PHP

  • By Daniyal Hamid
  • July 20, 2018
  • Comments
In This Article

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)
  • null
  • Resource
  • Object

Important stuff to remember about converting to an array:

  1. 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.
  2. Converting null to an array results in an empty array.
  3. 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.

If there's anything you would like to add, please let us know in the comments section.