In the process of web application development, passing parameters through GET is a very common operation. In PHP, converting arrays into URL parameters is a more practical and convenient strategy. This article will introduce how to Convert the array into URL parameters.
1. Use the http_build_query function
The http_build_query function is a built-in function in PHP that can convert an array into a URL parameter.
The syntax of this function is as follows:
string http_build_query ( mixed $query_data [, string $numeric_prefix [, string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] )
Among them, the query_data parameter is required and is the array to be converted.
The sample code is as follows:
$data = array( 'name' => 'Tom', 'age' => 28, 'email' => 'test@example.com' ); $url = 'http://www.example.com?' . http_build_query($data); echo $url;
Running the above code will get the following results: http://www.example.com?name=Tom&age=28&email=test@example.com
2. Manually splicing URL parameters
If you are more interested in manually splicing URL parameters, you can achieve it through the following sample code:
$data = array( 'name' => 'Tom', 'age' => '28', 'email' => 'test@example.com' ); $url = 'http://www.example.com?'; foreach ($data as $key => $value) { $url .= $key . '=' . urlencode($value) . '&'; } $url = rtrim($url, '&'); echo $url;
Running the above code will get the following results: http ://www.example.com?name=Tom&age=28&email=test@example.com
When manually splicing URL parameters, you need to pay attention to the escaping issues of spaces, slashes, Chinese and other characters. Therefore it is best to use the urlencode function to escape parameters.
3. Ending
Converting arrays into URL parameters is a very common requirement. The above method is relatively simple and practical. In actual development, one of the methods can be selected depending on the required parameters.
The above is the detailed content of How to convert array into URL parameters in PHP. For more information, please follow other related articles on the PHP Chinese website!