What is the correct syntax for passing key-value pairs in a URL in PHP?
When passing key-value pairs in a URL in PHP, you can use the `http_build_query()` function to convert an array of key-value pairs into a URL-encoded query string. This function takes an associative array as input and returns a string in the format key1=value1&key2=value2. This is useful when constructing URLs for API requests or passing data between different pages.
// Define an associative array of key-value pairs
$data = array(
'key1' => 'value1',
'key2' => 'value2'
);
// Convert the array into a URL-encoded query string
$queryString = http_build_query($data);
// Append the query string to the base URL
$url = 'http://example.com/api?' . $queryString;
// Output the final URL
echo $url;
Keywords
Related Questions
- How can PHP developers effectively troubleshoot issues related to displaying and processing data from checkboxes in a form submission scenario?
- What is the purpose of using the shuffle() function in PHP and how does it affect the array values?
- How can debugging techniques be used effectively to troubleshoot PHP code that interacts with a database?