Jump to content

Will someone explain this code to me in words?


cgm225

Recommended Posts

I am working through a tutorial here, and came across these lines of code::

 

$page = !empty($_GET["page"]) ? $_GET["page"] : "home";

$action = !empty($_GET["action"]) ? $_GET["action"] : "index";

 

What do they mean?  I do not understand what that syntax means, particularly the question mark and colon with the trailing "home" or "index". 

 

Will someone explain this code to me in words?

This is a Ternary Operator -- a sort of short-hand for if-else.  The first

<?php
$page = !empty($_GET["page"]) ? $_GET["page"] : "home";
?>

is the same as

<?php
if (!empty($_GET['page']))
   $page = $_GET['page'];
else
   $page = 'home';
?>

 

Ken

This is the ternary operator. Explanation in the manual:

http://www.php.net/manual/en/language.operators.comparison.php

(Scroll down a bit)

 

 

Basically, this:

$page = !empty($_GET["page"]) ? $_GET["page"] : "home";

 

Is the same as:

if(!empty($_GET["page"]))
  $page = $_GET["page"];
else
  $page = "home";

 

 

Orio.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.