vote up 1 vote down
star

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
offensive?
add comment

3 Answers:

vote up 6 vote down
check

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|offensive?
comments (1)
vote up 2 vote down

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|offensive?
comments (2)
vote up 0 vote down

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|offensive?
add comment

Your Answer:

Get an OpenID
or

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