Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - create array from string

I have a string that looks like:

single=Single&multiple=Multiple2&check=check1&radio=radio2

how could I create a array like this:

array(
  'single' => 'Single',
  'multiple' => 'Multiple2',
  'check' => 'check1',
  'radio' => 'radio2',
)
like image 860
Alex Avatar asked Jan 29 '11 18:01

Alex


People also ask

Can an array be created from a string?

We can have an array with strings as its elements. Thus, we can define a String Array as an array holding a fixed number of strings or string values. String array is one structure that is most commonly used in Java. If you remember, even the argument of the 'main' function in Java is a String Array.

Which function in PHP allow you to convert a string to an array?

PHP | str_split() Function The str_split() is an inbuilt function in PHP and is used to convert the given string into an array.


2 Answers

Use parse_str

parse_str('single=Single&multiple=Multiple2&check=check1&radio=radio2', $data);

And in $data you will have your variables.

like image 198
Radek Benkel Avatar answered Oct 05 '22 05:10

Radek Benkel


If this comes from an URL you can have this already as an array in the $_GET or $_POST variables. Otherwise use explode() to convert string to an array.

like image 21
Elzo Valugi Avatar answered Oct 05 '22 03:10

Elzo Valugi