String "array" for the real array

Now I got an array string, for example:

$str = "array('a'=>1, 'b'=>2)";

How to convert this string to a real array? Is there any “smart way” for this, others that use explode ()? Since the array "string" can be very complex for a while.

Thank!

+5
source share
6 answers

I do not know how to do this (only evil eval() must be avoided ).

but: where do you get this line? Is it something you can touch? if so, using serialize()/ unserialize()would be much better.

+5
source

Use php function "eval".

 eval("\$myarray = $str;");
+5
source

eval().

, eval() , json_encode()/json_decode().

+1

, eval. , .

$arr = eval($array_string);

, eval() !

, serialize unserialize.

+1

, .php.

php , .

+1

Do not use eval()in any case, just call strtoarray($str, 'keys')for an array with keys and strtoarray($str)for an array that has no keys.

function strtoarray($a, $t = ''){
    $arr = [];
    $a = ltrim($a, '[');
    $a = ltrim($a, 'array(');
    $a = rtrim($a, ']');
    $a = rtrim($a, ')');
    $tmpArr = explode(",", $a);
    foreach ($tmpArr as $v) {
        if($t == 'keys'){
            $tmp = explode("=>", $v);
            $k = $tmp[0]; $nv = $tmp[1];
            $k = trim(trim($k), "'");
            $k = trim(trim($k), '"');
            $nv = trim(trim($nv), "'");
            $nv = trim(trim($nv), '"');
            $arr[$k] = $nv;
        } else {
            $v = trim(trim($v), "'");
            $v = trim(trim($v), '"');
            $arr[] = $v;
        }
    }
    return $arr;
}
0
source

All Articles