Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialized string to array in PHP

Tags:

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?

like image 703
David Weng Avatar asked Dec 02 '22 02:12

David Weng


2 Answers

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
like image 53
3 revs, 3 users 45% Avatar answered Dec 03 '22 16:12

3 revs, 3 users 45%


Use parse_str :)

like image 42
Shay Ben Moshe Avatar answered Dec 03 '22 16:12

Shay Ben Moshe