'Converting array to string and then back in PHP

I created a array using PHP

$userarray = array('UserName'=>$username,'UserId'=>$userId,'UserPicURL'=>$userPicURL);

How can I convert this array into a string in PHP and back from string into an array. This is kind of a requirement. Could someone please advice on how this can be acheived.



Solution 1:[1]

You can convert any PHP data-type but resources into a string by serializing it:

$string = serialize($array);

And back into it's original form by unserializing it again:

$array = unserialize($string);

A serialized array is in string form. It can be converted into an array again by unserializing it.

The same does work with json_encode / -_decode for your array as well:

$string = json_encode($array);
$array = json_decode($string);

Solution 2:[2]

use the function implode(separator,array) which return a string from the elements of an array.

and then the function explode ( string $delimiter , string $string [, int $limit ] ) to revert it back to an array

$array_as_string = implode(" ",$userarray);
$new_array = explode(" ",$array_as_string);

Solution 3:[3]

You can use either

$userarray = array('UserName' => $username, 'UserId' => $userId, 'UserPicURL' => $userPicURL);
$string = json_encode($userarray);
$backtoarray = json_decode($string);

or

$userarray = array('UserName' => $username, 'UserId' => $userId, 'UserPicURL' => $userPicURL);
$string = serialize($userarray);
$backtoarray = unserialize($string);

The first one uses XML storage, and the second uses JSON.

Solution 4:[4]

this worked for me to get array again:

$backtoarray = (array) json_decode($string);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Alex
Solution 3 Greenisha
Solution 4 Elminson De Oleo Baez