17

I have an array:

$myArray = array('key1'=>'value1', 'key2'=>'value2');

I save it as a variable:

$fileContents = var_dump($myArray);

How can convert the variable back to use as a regular array?

echo $fileContents[0]; //output: value1
echo $fileContents[1]; //output: value2
trejder
  • 17,148
  • 27
  • 124
  • 216
Peter Craig
  • 7,101
  • 19
  • 59
  • 74
  • If you use `print_r` instead of `var_dump`, you can use [print_r reverse function](http://www.php.net/manual/en/function.print-r.php#93529). – machineaddict Jul 18 '13 at 07:35

6 Answers6

27

I think you might want to look into serialize and unserialize.

$myArray = array('key1'=>'value1', 'key2'=>'value2');
$serialized = serialize($myArray);
$myNewArray = unserialize($serialized);
print_r($myNewArray); // Array ( [key1] => value1 [key2] => value2 ) 
Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
  • 3
    But it's not an answer for the question. – marines Jan 25 '13 at 13:26
  • 6
    Your solution doesn't cover reverting var_dump() output to array (this was the question). It's just another way to accomplish serializing and unserializing an array. – marines Jan 28 '13 at 20:23
  • 5
    @marines: If you want to take a literal approach to the question, I guess that's true. It's pretty clear the OP was just looking for a way to save an array as a string and then bring it back, so serialize is the correct answer to his *problem*, even if the question did not specify it. You'd never do what he's trying to do with var_dump() intentionally, so it becomes a non issue. – Paolo Bergantino Jan 28 '13 at 20:37
  • 1
    @Paolo Bergantino: I have a response from a remote online service who displays the result as string representation of an array. How do I revert that back into an array??? – machineaddict Jul 18 '13 at 07:24
  • 1
    Actually @marines, the OP DID specify it: He gave the example of var_dump() which can't gotten back to life with unserialize. He is looking for a way to reverse engineer a var_dump() to make an usable array out of it. – sergio Aug 01 '15 at 11:52
26

serialize might be the right answer - but I prefer using JSON - human editing of the data will be possible that way...

$myArray = array('key1'=>'value1', 'key2'=>'value2');
$serialized = json_encode($myArray);
$myNewArray = json_decode($serialized, true);
print_r($myNewArray); // Array ( [key1] => value1 [key2] => value2 )
Rain
  • 3,416
  • 3
  • 24
  • 40
Binny V A
  • 2,036
  • 3
  • 20
  • 23
  • 1
    +1, I don't know why I didn't think about it initially. This is what I personally use too. – Paolo Bergantino Mar 26 '09 at 14:00
  • 5
    +1 for the use of JSON. Note: the json_decode() function needs the 2nd parameter to be "true" to return an associative array! (or it will return a "stdClass" object) – J.C. Inacio Mar 26 '09 at 15:43
8

Try using var_export to generate valid PHP syntax, write that to a file and then 'include' the file:

$myArray = array('key1'=>'value1', 'key2'=>'value2');
$fileContents = '<?php $myArray = '.var_export($myArray, true).'; ?>';

// ... after writing $fileContents to 'myFile.php'

include 'myFile.php';
echo $myArray['key1']; // Output: value1
Jake McGraw
  • 55,558
  • 10
  • 50
  • 63
  • Every should forget about using $myArray as the source for any example here. The OP clearly said he wants to start from a dump of it, not the actual array. He has a string with the dump, not the array. He doesn't want to generate the string. – sergio Aug 01 '15 at 11:55
4

How about eval? You should also use var_export with the return variable as true instead of var_dump.

$myArray = array('key1'=>'value1', 'key2'=>'value2');
$fileContents = var_export($myArray, true);
eval("\$fileContentsArr = $fileContents;");
echo $fileContentsArr['key1']; //output: value1
echo $fileContentsArr['key2']; //output: value2
KRavEN
  • 351
  • 2
  • 7
  • Another example that uses $myArray when the OP stated he wants to use the var_dump() of it. NOT the array. In what it concerns to us, the array might be already gone and he only is mentioning it for us to know what the dump was of. – sergio Aug 01 '15 at 11:57
4
$array = ['10', "[1,2,3]", "[1,['4','5','6'],3]"];

function flat($array, &$return) {
    if (is_array($array)) {
        array_walk_recursive($array, function($a) use (&$return) { flat($a, $return); });
    } else if (is_string($array) && stripos($array, '[') !== false) {
        $array = explode(',', trim($array, "[]"));
        flat($array, $return);
    } else {
        $return[] = $array;
    }
}

$return = array();

flat($array, $return);

print_r($return);

OUTPUT

Array ( [0] => 10 [1] => 1 [2] => 2 [3] => 3 [4] => 1 [5] => '4' [6] => '5' [7] => '6'] [8] => 3 )
Nady Shalaby
  • 604
  • 7
  • 7
2

Disclaimer

I wrote this function (out of fun:) and because I'm lazy AF I wanted a short way to convert an array inside a string to a valid PHP array. I'm not sure if this code is 100% safe to use in production as exec and it's sisters always scare the crap out of me.

$myArray = 'array("key1"=>"value1", "key2"=>"value2")';

function str_array_to_php(string $str_array) {
    // No new line characters and no single quotes are allowed
    $valid_str = str_replace(['\n', '\''], ['', '"'], $str_array);
    exec("php -r '
    if (is_array($valid_str)) {
        function stap(\$arr = $valid_str) {
            foreach(\$arr as \$v) {
                if(is_array(\$v)){
                    stap(\$v);
                }
                else {
                    echo \$v,PHP_EOL;
                }
            }
        }
        stap();
    }'2>&1", $out);
        return $out;
}

print_r(str_array_to_php($myArray));

Output:

Array ( [0] => value1 [1] => value2 ) 

As you can see, it will convert $myArray into a valid PHP array, and then indexes it numerically and if it is multidimensional it will convert it into single one.

BE CAREFUL:

1- never pass the array in double quotes as this will allow null byte characters (\0) to be evaluated.

For example:

$myArray = "array(\"key1\"=>\"value\n\0 ggg\", \"key2\"=>\"value2\")"
//Output: Warning: exec(): NULL byte detected. Possible attack

2- This function wont work if exec is disabled (Mostly will be )

3- This function wont work if php command is not set

One last thing, if you find any error or flaws please let me know in the comments so i can fix it and learn.

Hope this helps.

Rain
  • 3,416
  • 3
  • 24
  • 40