up vote 2 down vote favorite

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
flag

65% accept rate

4 Answers

up vote 10 down vote accepted

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 )
link|flag
Cheers, works perfectly. – Peter Mar 26 '09 at 5:20
up vote 3 down vote

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 )
link|flag
+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
+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 Mar 26 '09 at 15:43
up vote 0 down vote

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
link|flag
up vote 0 down vote

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
link|flag

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.