How to cast variable to array

You can cast a variable to an array by using:

    $var = (array)$arr;

$a = (array) $v;

is the answer.


I would write your could snippet like this (short and you read it and know exactly what is happening):

$a = is_array($v) ? $v : array($v);

Alternatively you could use settype:

settype($a, "array");

For expliciting the variable type. It's exactly the same as what happens with a typecast behind the scenes. (More useful for group-wise typecasting e.g. in loops.)


If you are looking to convert an object to a single count array you can use the follow code:

$list = array([0] => $obj);

The other provided answers won't work when trying to convert an object, it will simply convert the fields of that object into an associative array (unless that is what you are trying to do).

$var = (array)$arr;