I have a website URL like the following:
www.localhost.com/page?x=1&y=2
Now I want to get all the GET parameters in an array like below:
$array[0] = 1;
$array[1] = 2;
Thanks.
I have a website URL like the following:
www.localhost.com/page?x=1&y=2
Now I want to get all the GET parameters in an array like below:
$array[0] = 1;
$array[1] = 2;
Thanks.
You can read from global $_GET directly and create array with keys:
$array = [
'y' => $_GET['y'],
'x' => $_GET['x'],
];
You can use $_GET global variable in PHP itself.
$array = [];
foreach($_GET as $key => $value) {
array_push($array, $value);
}
You can use PHP array_values()
if you want to get all the values of that array without considering the keys:
$array = array_values($_GET);
You can also use the newer syntax:
$array = [];
foreach($_GET as $key => $val)
{
$array[$key] = $value;
}
You can also use PHP's built-in array_values() function to accomplish the same thing. Per the documentation:
Returns an indexed array of values.
This will maintain the order of values as they originally were in the $_GET
array. For example:
/**
* With $_GET input array of:
*
* ['a' => 'apple', 'c' => 'cantaloupe', 'b' => 'banana']
*/
$indexed = array_values($_GET);
/**
* Will output an indexed array of:
*
* [0 => 'apple', 1 => 'cantaloupe', 2 => 'banana']
*/
Note that this maintains the original sort order and will not reindex the output array (even if your associative array keys are numeric).
?x=2&y=3
.
array_values
function operates very similarly to a foreach loop and does not modify the order. There does exist a possibility of inconsistent ordering due to browsers, javascript frameworks, and even caching layers like CloudFlare. For that reason, you should really consider a less brittle solution.
Jan 7, 2019 at 19:12
$array = [$_GET['x'], $_GET['y']]
if you know which parameters will be passed. Perhaps though order isn't important here.