Home » Php » php – String "array" to real array

php – String "array" to real array

Posted by: admin July 12, 2020 Leave a comment

Questions:

Now I got the string of an array, like this :

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

How can I convert this string into real array ? Is there any “smart way” to do that, other that use explode() ? Because the “string” array could be very complicated some time.

Thanks !

How to&Answers:

i don’t know a good way to do this (only evil eval() wich realy should be avoided).

but: where do you get that string from? is it something you can affect? if so, using serialize() / unserialize() would be a much better way.

Answer:

Use php’s “eval” function.

 eval("$myarray = $str;");

Answer:

You’d have to use eval().

A better way to get a textual representation of an array that doesn’t need eval() to decode is using json_encode() / json_decode().

Answer:

You could write the string to a file, enclosing the string in a function definition within the file, and give the file a .php extension.

Then you include the php file in your current module and call the function which will return the array.

Answer:

Don’t use eval() in any case
just call strtoarray($str, 'keys') for array with keys and strtoarray($str) for array which have 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;
}

Answer:

If you can trust the string, use eval. I don’t remember the exact syntax, but this should work.

$arr = eval($array_string);

If the string is given by user input or from another untrusted source, you should avoid eval() under all circumstances!

To store Arrays in strings, you should possibly take a look at serialize and unserialize.

Answer:

With a short version of the array json_decode works

json_decode('["option", "option2"]')

But with the old version just like the OP’s asking it doesn’t. The only thing it could be done is using Akash’s Answer or eval which I don’t really like using.

json_decode('array("option", "option2")')