0

I want to know what URL user has accessed. For example, if user accessed:

index.php?register

it will echo '1'.

if (isset($_GET))
{
    switch ($_GET)
    {
        case "register":
            echo 1;
        break;
    }
}

But it doesn't do anything, why? How do you get the name of the first GET element?

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • `var_dump($_GET)` to see what is there. – Naftali Jul 17 '13 at 13:57
  • 2
    You are case-ing where `$_GET = register` which is never true. You need to foreach through the array in key=>value pairs to check where `switch($key) { case "register" ` – Royal Bg Jul 17 '13 at 13:57
  • `array_keys`, `$_REQUEST`, `isset($_GET['register'])`, `array_key_exists($_GET, 'register')`... tried any of those? – Elias Van Ootegem Jul 17 '13 at 13:58
  • if you want to do it on-fly, try: array_keys($GET) – Rikky Jul 17 '13 at 13:58
  • `$_GET` is an array. You need to loop through it and read the key(s). – gen_Eric Jul 17 '13 at 13:59
  • 1
    1. `$_GET` is always set. 2. `$_GET` is an array and can't be used as `string`. 3. You may want to have: `index.php?act=register` and use `switch ($_GET['act']) {...}`. 4. 3 is fast solution but awful. – Leri Jul 17 '13 at 13:59

4 Answers4

4

$_GET is an array. You'd need to place that switch statement inside a foreach loop:

foreach ($_GET as $k => $v) {
    switch ($k) {
        case 'register':
            echo 1;
        break;
    }
}

Also, the $_GET superglobal is always set – there's no need for if (isset($_GET)) {

Terry Harvey
  • 840
  • 6
  • 12
3

You could use array_keys() to get the keys for each $_GET, then use the 0 index to determine what you wanted to do with the first key:

if($_GET){
    $keys = array_keys($_GET);
    switch ($keys[0]){
        case "register":
            echo 1;
        break;
    }   
}
Samuel Cook
  • 16,620
  • 7
  • 50
  • 62
1

$_GET is a superglobal array. It's always set, and always an array.

If you know that register will always be the 1st GET element, then you can do this:

reset($_GET);
switch (key($_GET)){
    case "register":
        echo 1;
    break;
}

Docs for key(): http://php.net/key

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
-3

$_GET is an associative array, so it's structured in key=value elements

you can either use this URL: index.php?page=register with this code:

if (isset($_GET['page']))
{
    switch ($_GET['page'])
    {
        case "register":
            echo 1;
        break;
    }
}

OR with this URL index.php?register use this code:

foreach ($_GET as $key => $value) {
    switch ($key) {
        case 'register':
            echo 1;
        break;
    }
}
Ghilas BELHADJ
  • 13,412
  • 10
  • 59
  • 99