PHP has built in function http_build_query that can be used to prepare a query string from an array.
Instead of explicitly appending elements to string, this function comes handy, which takes cares of generating URL-encoded query string either from an associative or indexed array.
Also it works with an object, comprising of public properties only into final query string.
Supported in PHP >= 5
Example 1
$data = [
'search' => 'cars',
'sourceType' => 'image',
];
echo http_build_query($data);
/*
* Output
*
* "search=cars&sourceType=image"
*/
Example 2
$data = [
'firstName' => 'Shirley',
'lastName' => 'Setia',
'profession' => 'Singer',
'location' => [
'city' => 'Daman',
'state' => 'Gujarat',
'country' => 'India',
],
];
echo http_build_query($data);
/*
* Output
*
* "firstName=Shirley&lastName=Setia&profession=Singer&location%5Bcity%5D=Daman&location%5Bstate%5D=Gujarat&location%5Bcountry%5D=India"
*/
Hope you find it useful.
Happy coding
Related Articles
Deepen your understanding with these curated continuations.
PHP Interview Questions
This tutorial explains with syntax and an example of how to flatten a multi-dimensional array based on the value of depth specified in the Laravel framework.
Convert Hex Color to RGB or RGBA in PHP
A PHP helper function that converts any hex color code to rgb() or rgba() โ handles 3-char shorthand, optional opacity, and the # prefix. With usage examples.
How to find the array index key of multi-dimensional array
How to find the array index key of multi-dimensional array