-2

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.

2

4 Answers 4

2

You can read from global $_GET directly and create array with keys:

$array = [
 'y' => $_GET['y'],
 'x' => $_GET['x'],
];
0

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);
0
0

You can also use the newer syntax:

$array = [];
foreach($_GET as $key => $val)
{
    $array[$key] = $value;
}
3
  • 1
    Why should one do that and not directly use $_GET?
    – Nico Haase
    Jan 7, 2019 at 15:10
  • This makes just a copy of the references in $_GET in $array with the same indices.
    – Al.G.
    Jan 7, 2019 at 16:18
  • Is there a difference between the above and $array = $_GET ? This array is also not numerically indexed.
    – Progrock
    Jan 7, 2019 at 18:59
0

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).

3
  • This was my first thought. But I'd have thought order likely important here. Parameters could be re-ordered leading to different results. ?x=2&y=3.
    – Progrock
    Jan 7, 2019 at 19:02
  • No, the 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
  • That's exactly what I meant. I'd go with $array = [$_GET['x'], $_GET['y']] if you know which parameters will be passed. Perhaps though order isn't important here.
    – Progrock
    Jan 7, 2019 at 19:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy