Home >Backend Development >PHP Tutorial >How Can I Easily Pass Arrays as URL Parameters in PHP?
Passing Arrays as URL Parameters: A Simple Solution
Passing arrays as URL parameters can be a daunting task, but with the right tools, it can be made simple. The issue at hand involves determining the best method to pass an array as a URL parameter. The options presented are cumbersome and messy.
Fortunately, there is a straightforward solution: http_build_query(). This function takes query parameters as an associative array.
Consider the following example:
$data = array( 1, 4, 'a' => 'b', 'c' => 'd' ); $query = http_build_query(array('aParam' => $data));
The result will be:
string(63) "aParam%5B0%5D=1&aParam%5B1%5D=4&aParam%5Ba%5D=b&aParam%5Bc%5D=d"
This string is equivalent to:
aParam[0]=1&aParam[1]=4&aParam[a]=b&aParam[c]=d
http_build_query() takes care of the necessary escaping ([ => [ and ] => ]), making URL encoding easy and efficient.
The above is the detailed content of How Can I Easily Pass Arrays as URL Parameters in PHP?. For more information, please follow other related articles on the PHP Chinese website!