How can i convert a multidimensional array to string and vice versa?

Hi…

I have a multi dimensional array i want to convert this array to string and saved in to a file.Also need to convert string that stored in the file to the previous array for further processing. (i.e the file is like a table in the database ). Is it possible to convert the array to string and then back to array using php?
If anyone knows please help me thanks in advance…

Sure, [fphp]serialize[/fphp] should do what you ask. :slight_smile:

Depending on your needs you could probably use [fphp]json_encode[/fphp] and [fphp]json_decode[/fphp] to achieve similar too, not sure if it might be a bit “lossy” but for arrays it should be ok.


$test = array(1=>'this',10=>'that','a key'=>'the other', 'we dont need no stinkin key');

// encoding
$a = json_encode($test);

echo $a;
//{"1":"this","10":"that","a key":"the other","11":"we dont need no stinkin key"}
// assigns key 11 to the array

// now decoding
$b = json_decode( $a, true);

var_dump($b);

//array
//  1 => string 'this' (length=4)
//  10 => string 'that' (length=4)
//  'a key' => string 'the other' (length=9)
// 11 => string 'we dont need no stinkin key' (length=27)


var_dump( array_diff( $test, $b) );
// array empty
// even though $test's 4th item had no key

Use json_decode with 2nd argument empty to get a class returned instead of an array.

I tested with a multidimensional array too and it works the same.

<?php file_put_contents( 'somefile', '<?php return ' . var_export( $array, true ) . '; ?>' );

//....further down....

$array = include 'somefile';

:smiley:

Cor! I like that.