David Weng
David Weng

Reputation: 4245

Serialized string to array in PHP

I receive a string from jQuery UI Sortable plugin, it gives me a string like this one

items[]=1&items[]=2&items[]=3

How can I trun it into a real array?

I was thinking replacing & with ; and asserting it. Any better suggestions?

Upvotes: 5

Views: 7205

Answers (3)

Syed Shah
Syed Shah

Reputation: 1

// I am assuming you are getting this value from post or get method;

$string = implode(";", $_REQUEST['items']);
echo $string;

Upvotes: -1

Pekka
Pekka

Reputation: 449823

You are looking for parse_str().

Parses str as if it were the query string passed via a URL and sets variables in the current scope.

For example:

$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

You can also specify an array to store results in if you do not want to pollute your scope:

parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

Upvotes: 21

Shay Ben-Moshe
Shay Ben-Moshe

Reputation: 1296

Use parse_str :)

Upvotes: 1

Related Questions