views:

1603

answers:

4

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
A: 

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
jakemcgraw
+10  A: 

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
Cheers, works perfectly.
Peter
+4  A: 

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);
print_r($myNewArray); // Array ( [key1] => value1 [key2] => value2 )
Binny V A
+1, I don't know why I didn't think about it initially. This is what I personally use too.
Paolo Bergantino
+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)
jcinacio
A: 

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