0

I'm digging up a code I used to write with a friend of mine. It's been a while and I can't figure out what the purpose was of this snippet:

$page = isset($_REQUEST['page']) ? $_REQUEST['page'] : "home.php";

It's nearly the only code in that php-file.

Thanks a lot.

Sirko
  • 72,589
  • 19
  • 149
  • 183
binoculars
  • 2,226
  • 5
  • 33
  • 61

5 Answers5

2

It is the same as

if (isset($_REQUEST['page'])){
  $page = $_REQUEST['page'] ;
} else {
  $page = "home.php" ;
}

It is called Ternary operator. Provides some readability for you code.

(expr) ? (value if true) : (value if false)
sybear
  • 7,837
  • 1
  • 22
  • 38
2

Basically it is ternary operator that checks for the condition that whether the page variable is set either by POST method or GET method.REQUEST method can check both.and if it is set then the request page value $_REQUEST['page'] will be assigned to $page variable or else defaultly 'home.php' will be assigned to the $page same as

if (isset($_REQUEST['page'])){
     $page = $_REQUEST['page'] ;
} else {
     $page = "home.php" ;
}
GautamD31
  • 28,552
  • 10
  • 64
  • 85
2

First of all try to read a bit about Superglobals to understand why and when you use $_REQUEST Then check the method isset() And finally the sintax for your if statement wich is

if(condition) doSomething else doSomething;

So basically you check if $_REQUEST['page'] has a value (is not null or unset). If it has, you put that value into the variable $page. Else, you set $page with the value "home.php.

Hope it helped!

VladH
  • 383
  • 4
  • 16
1

This is a ternary operator. Its a single line if statement.

Read it like this

if (isset($_REQUEST['page'])) {
    $page = $_REQUEST['page'];
} else {
    $page = 'home.php';
}
fullybaked
  • 4,117
  • 1
  • 24
  • 37
1

This is the ternary operator, the form is:

test ? true-value : false-value

It evaluates the part of the expression before ?. If it's true, the true-value expression is evaluated and returned, otherwise the false-value expression is evaluated and returned.

So your code checks whether $_REQUEST['page'] is set. If it is, $page is set to its value, otherwise $page is set to home.php.

$_REQUEST is a predefined variable that contains the parameters set from either the URL (like $_GET) or form fields (like $_POST').

Barmar
  • 741,623
  • 53
  • 500
  • 612