PHP function to build query string from array

Php

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

You're looking for http_build_query().

Solution 2 - Php

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[] = urlencode( $key ) . '=' . urlencode( $key_value );
		
	}
	
	return implode( '&', $query_array );

}

Solution 3 - Php

Just as addition to @thatjuan's answer.
More compatible PHP4 version of this:

if (!function_exists('http_build_query')) {
    if (!defined('PHP_QUERY_RFC1738')) {
        define('PHP_QUERY_RFC1738', 1);
    }
    if (!defined('PHP_QUERY_RFC3986')) {
        define('PHP_QUERY_RFC3986', 2);
    }
    function http_build_query($query_data, $numeric_prefix = '', $arg_separator = '&', $enc_type = PHP_QUERY_RFC1738)
    {
        $data = array();
        foreach ($query_data as $key => $value) {
            if (is_numeric($key)) {
                $key = $numeric_prefix . $key;
            }
            if (is_scalar($value)) {
                $k = $enc_type == PHP_QUERY_RFC3986 ? urlencode($key) : rawurlencode($key);
                $v = $enc_type == PHP_QUERY_RFC3986 ? urlencode($value) : rawurlencode($value);
                $data[] = "$k=$v";
            } else {
                foreach ($value as $sub_k => $val) {
                    $k = "$key[$sub_k]";
                    $k = $enc_type == PHP_QUERY_RFC3986 ? urlencode($k) : rawurlencode($k);
                    $v = $enc_type == PHP_QUERY_RFC3986 ? urlencode($val) : rawurlencode($val);
                    $data[] = "$k=$v";
                }
            }
        }
        return implode($arg_separator, $data);
    }
}

Solution 4 - Php

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobin BarnesView Question on Stackoverflow
Solution 1 - PhpTJ LView Answer on Stackoverflow
Solution 2 - Php0x6A75616EView Answer on Stackoverflow
Solution 3 - Phpvp_arthView Answer on Stackoverflow
Solution 4 - PhpAliView Answer on Stackoverflow