Online Snippets Library

How to use Ternary Operator In PHP

Ternary Operator takes three operands - a condition, a result if condition true, and a result if condition false.

It makes our code shorter and easier to maintain.

We will start with an simple example.

Syntax

(condition) ? (result_if_true) : (result_if_false)

Example

<?php
$message = 'Hello '.(isLoggedIn() ? $this->get('firstName') : 'Guest User');
?>

Example

<?php
$ageVarible = ($age < 16) ? 'Child' : 'Adult';
?>