Tag Archives: ternary operators

PHP ternary operators and how to use them


I’ll add more to this note as I find the need.  Something I already use, but as of PHP7, there are a few little newbies that it doesn’t hurt to note down.

I like this one.  It replaces the isset() clause.

So this:

if(isset($_POST['something']){$something= $_POST['something'];}

Can now be written (in PHP7+):

$something= $_POST['something'] ?? "default";

The above fetches the POST content if it exists, and defaults to the ” ” enclosed value if it doesn’t.

Some more examples of ternary operators:

$isABigNumber = ($number < 1000 ? "Small Number" : "Big Number")


Share this post:
read more