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 Reading.
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.
PHP - Ternary Operator
PHP - Ternary Operator
Get Last Array Element in PHP and Laravel
This article, guide you through the retrieval of last array element in different ways in Laravel and also in PHP.