Often, there are situations where you need to pass an array to a script via a URL parameter. There are various approaches to this problem, each with its own advantages and disadvantages.
Naive Approaches
Attempting to pass an array as a URL parameter without any processing can lead to messy results. Concatenating the values into a single string results in an unwieldy parameter:
$url = 'http://www.example.com?aParam[]=value1&aParam[]=value2&aParam[]=value3';
The http_build_query() Function
Fortunately, PHP provides a convenient solution: the http_build_query() function. It takes an associative array as input and returns a URL-encoded query string.
$data = array( 1, 4, 'a' => 'b', 'c' => 'd' ); $query = http_build_query(array('aParam' => $data));
This will produce the following query string:
aParam%5B0%5D=1&aParam%5B1%5D=4&aParam%5Ba%5D=b&aParam%5Bc%5D=d
Notice how the function automatically handles the necessary escaping ([ => [ and ] => ]). This ensures that the query string is correctly formed.
The above is the detailed content of How Can I Efficiently Pass Arrays as URL Parameters in PHP?. For more information, please follow other related articles on the PHP Chinese website!