Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm looking for the name of the PHP function to build a query string from an array of key value pairs. Please note, I am looking for the built in PHP function to do this, not a homebrew one (that's all a google search seems to return). There is one, I just can't remember its name or find it on php.net. IIRC its name isn't that intuitive.

share|improve this question

5 Answers

up vote 121 down vote accepted

You're looking for http_build_query().

share|improve this answer
Yeah, that's the one. – Robin Barnes Dec 30 '08 at 17:00
Wish I'd known about that function a long time ago. Heh. – ceejayoz Dec 30 '08 at 17:17
3  
+1, but the your/you're is hurting my soul – Andrew Heath Feb 23 '11 at 9:23
1  
Never knew about this. Super! – Carpetsmoker Mar 15 '11 at 23:27
1  
+1 because I found it here faster than I could find it on php.net – TecBrat Jun 5 at 15:47
show 3 more comments

Here's a simple php4-friendly implementation:

/**
* Builds an http query string.
* @param array $query  // of key value pairs to be used in the query
* @return string       // http query string.
**/
function build_http_query( $query ){

    $query_array = array();

    foreach( $query as $key => $key_value ){

        $query_array[] = $key . '=' . urlencode( $key_value );

    }

    return implode( '&', $query_array );

}
share|improve this answer
   
I guess you didn't see the accepted answer? – John Conde May 13 '11 at 20:09
12  
this is a php4 version. – thatjuan May 13 '11 at 21:08

I'm not aware of a builtin function, but there is the PECL class http://uk.php.net/manual/en/class.httpquerystring.php

share|improve this answer

Implode will combine an array into a string for you, but to make an SQL query out a kay/value pair you'll have to write your own function.

share|improve this answer
Tried that but it won't work. I'm trying to build an http query string which requires both the keys and the values from the array, implode can't do this. – Robin Barnes Dec 30 '08 at 17:00
1  
I see, wasn't sure if you meant an SQL query string or a http query string. – Click Upvote Dec 30 '08 at 21:05

but for inverse this work, you can use :

void parse_str(str $input, array $output);
//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

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

Good luck.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.