Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting array to string and then back in PHP

Tags:

arrays

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.

like image 367
Abishek Avatar asked Jun 24 '11 09:06

Abishek


People also ask

What is implode and explode function in PHP?

Definition and UsageThe implode() function returns a string from the elements of an array. Note: The implode() function accept its parameters in either order. However, for consistency with explode(), you should use the documented order of arguments. Note: The separator parameter of implode() is optional.

What is the name of function used to convert an array into a string?

toString() The toString() method returns a string representing the specified array and its elements.

How we can convert a multidimensional array to string without any loop?

Maybe in case you need to convert a multidimensional array into a string, you may want to use the print_r() function. This is also called “array with keys”. By adding “true” as its second parameter, all the contents of the array will be cast into the string.


2 Answers

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);
like image 76
hakre Avatar answered Sep 30 '22 11:09

hakre


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);
like image 32
Alex Avatar answered Sep 30 '22 11:09

Alex