5

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.

1

4 Answers 4

11

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Note the difference between using serialize/unserialize vs imlpode/explode is that the former will work regardless of the contents of the values - with the example provided by Alex, the method will fail if one of the valuse contains a space
1

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);

Comments

0

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.

Comments

0

this worked for me to get array again:

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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.