Tag: ternary operator

Life of a developer

It has been a while since I have posted here, mainly due to the time consuming period that is the festive season and also because I am discovering that I am getting fairly annoyed by Drupal as a blog tool and am trying out the new WordPress as an alternative.

For now I have a small post on something that many people aren’t aware of but is VERY handy, the ternary operator.

Basically it is a shortcut to do a simple if-then-else statement in one line when you are performing fairly simple checks for a single value. I tend to use it a lot when checking for GET or POST variables.


$getContents = (isset($_GET) ? $_GET : array());

would check if the $_GET variable array is set, if it is return its contents to $getContents and if not return and empty array to $getContents.

Much easier that coding:

$getContents = array();
if (isset($_GET)){
$getContents = $_GET;

P.S. Just on a side note, if you are new to PHP and want to use this code to check for and receive your $_GET contents, dont forget to sanatize your data as well (hmm I think I see a new post topic)

Filed under: DevelopmentTagged with: ,