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
1

6 Answers 6

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 ) 
Sign up to request clarification or add additional context in comments.

5 Comments

But it's not an answer for the question.
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: 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: 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???
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.
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 )

2 Comments

+1, I don't know why I didn't think about it initially. This is what I personally use too.
+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)
9

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

1 Comment

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

1 Comment

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

Comments

4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.