Add to Favorites

PHP Ternary Operator

The ternary operator in php is a piece of code that provides some nice syntax for conditional logic.

It is very useful for shorthanding an if/else block for setting a default value of a variable.
For example:

$v = ( empty($_GET['v']) ? '1' : $_GET['v'] );

This little snippet sets variable $v equal to the value passed in on the query for 'v', but if that value passed in on the query is empty, it sets variable $v to 1;

Essentially it works like a regular conditional statement in that
( expression? true return value : false return value )
If expression returns true, the first value there is used, if it returns false the second value is used.

It also comes in handy for database inserts/updates, for example you want to use NULL in a foreign key relationship when the value of a variable is blank:

'update book set category_id = '. ( empty($cat_id) ? 'NULL' : intval($cat_id) ) .' where id = 2'


Be the first to leave a comment on this post.

Leave a comment

To leave a comment, please log in / sign up