Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a PHP function to convert a query string to an array?

Tags:

php

I'm basically looking for the opposite of http_build_query().

I have the following as a string:

foo=bar&bar[var]=foo 

And I want the following (to pass into http_build_query):

array(     'foo' => 'bar',     'bar' => array(          'var' => 'foo',     ) ) 
like image 309
Darryl Hein Avatar asked Oct 17 '10 00:10

Darryl Hein


People also ask

Which function will use to convert from string to array?

The str_word_count function converts a string to an array of words when passed a second argument.

Can you convert a string to an array?

We can also convert String to String array by using the toArray() method of the List class. It takes a list of type String as the input and converts each entity into a string array.

How convert string to array in PHP with explode?

1) Convert String to Array using explode()explode() method is one of the built-in function in PHP which can be used to convert string to array. The explode() function splits a string based on the given delimiter. A delimiter acts as a separater and the method splits the string where the delimiter exists.

What is $_ GET in PHP?

PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with method="get". $_GET can also collect data sent in the URL. Assume we have an HTML page that contains a hyperlink with parameters: <html> <body>


1 Answers

You want parse_str(). Pass it an array as the 2nd parameter and it will extract variables from the query string you give it into the array:

<?php $str = "first=value&arr[]=foo+bar&arr[]=baz";  parse_str($str, $output);  print_r($output);  /* Array (     [first] => value     [arr] => Array         (             [0] => foo bar             [1] => baz         )  ) */ 

Notice this is the very first related function listed on the http_build_query page.

like image 179
meagar Avatar answered Oct 24 '22 11:10

meagar