How to cast variable to array

泪湿孤枕 提交于 2019-12-18 04:28:06

问题


I have a variable $v that can be either single string or array of strings
and I have a code:

$a = array();
if (is_array($v)) {
    $a = $v;
} else {
    $a[] = $v;
}

How it can be done in more elegant way? (in other words, how to cast a variable to array)


回答1:


You can cast a variable to an array by using:

    $var = (array)$arr;



回答2:


$a = (array) $v;

is the answer.




回答3:


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);



回答4:


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.)




回答5:


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;



回答6:


As others have said, casting a scalar value to an array will produce a singleton array (i.e. an array with the scalar as its only element). However, as still others have pointed out, take care to only do this if you know the value is going to be a scalar and not a class instance.

From the PHP docs:

For any of the types integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue).

If an object is converted to an array, the result is 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.




回答7:


Actually if you want to cast to an array and not have to worry about what you put into it, the answer is

$var = (is_object($var)) ? array($var) : (array) $var;

You can test this with the following code

function toArray($var) {
    return (is_object($var)) ? array($var) : (array) $var;
}

$object = new stdClass;
$resource = fopen('php://stdout', 'w');
$closure = function () {};

$tests = array(
    array(toArray(true),      array(true),      'boolean true'),
    array(toArray(false),     array(false),     'boolean false'),
    array(toArray(null),      array(),          'null'),
    array(toArray(1),         array(1),         'positive integer'),
    array(toArray(0),         array(0),         'zero integer'),
    array(toArray(-1),        array(-1),        'negative integer'),
    array(toArray(1.5),       array(1.5),       'positive float'),
    array(toArray(0.0),       array(0.0),       'zero float'),
    array(toArray(-1.5),      array(-1.5),      'negative float'),
    array(toArray(''),        array(''),        'empty string'),
    array(toArray('foo'),     array('foo'),     'string'),
    array(toArray(array()),   array(),          'array'),
    array(toArray($object),   array($object),   'object'),
    array(toArray($resource), array($resource), 'resource'),
    array(toArray($closure),  array($closure),  'closure'),
);

foreach ($tests as $test) {
    ob_start();
    var_dump($test[0]);
    $a = ob_get_clean();
    ob_start();
    var_dump($test[1]);
    $b = ob_get_clean();
    assert($a === $b, "{$test[2]} is not the same");
}


来源:https://stackoverflow.com/questions/5970270/how-to-cast-variable-to-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!