-2

I am trying to display content depending on page id, however when I add nothing to the url, so just index.php I get an error saying that $p is not defined, how can I give this var a default value that's outside the switch case?

<?php
$p = $_GET['p'];
switch ($p) {
    case 1:
        $content1 = new login();
        $content = $content1->displayLogin();
        break;

    case 2:
        echo "ID is 2";
        break;

    case 3:
        echo "ID is 3";
        break;

    default:
        $content1 = new dbconnection();
        $content = $content1->displayTable();
}
Phiter
  • 14,570
  • 14
  • 50
  • 84
Eseffe
  • 1
  • 1
  • 5
    Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) – cteski Mar 19 '18 at 19:13
  • So really, you're asking how to assign a value to a variable? – Patrick Q Mar 19 '18 at 19:15
  • $p = ""; does not work @PatrickQ same for giving it value 0 or 20 (outside switch case) – Eseffe Mar 19 '18 at 19:16
  • Read the link in the first comment. You are trying to access an element of an empty array. – waterloomatt Mar 19 '18 at 19:17
  • 1
    Read your error carefully. Is it saying that the _variable_ `$p` is not defined or is it saying that the _index_ 'p' is undefined? – Patrick Q Mar 19 '18 at 19:18

3 Answers3

3

Replace:

$p = $_GET['p'];

With:

$p = !empty($_GET['p']) ? $_GET['p'] : default_id_value_here;
dukedevil294
  • 1,285
  • 17
  • 31
3

I understand that you want to make $p have a default value if $_GET['p'] is not defined.

You can do it like this:

$p = isset($_GET['p']) ? $_GET['p'] : 'defaultValue';

or, if you're on PHP 7:

$p = $_GET['p'] ?? 'defaultValue';
Phiter
  • 14,570
  • 14
  • 50
  • 84
1

You can do the following:

$p = $_GET['p'] ?? <default value>; // e.g 1 or 3 etc.

Read more about it at this question: PHP syntax question: What does the question mark and colon mean?

Cyril de Wit
  • 446
  • 4
  • 12