Skip to content

How to replace "if" statement with a ternary operator ( ? : )?

Here's how you can replace an "if" statement with a ternary operator in PHP:

Replacing an if-else statement with a ternary operator

php
<?php

$condition = true;

if ($condition) {
    $result = "expression1";
} else {
    $result = "expression2";
}

echo $result;

can be replaced with:

Ternary operator equivalent

php
<?php

$condition = true;

$result = ($condition) ? "expression1" : "expression2";

echo $result;

<div class="alert alert-info flex not-prose"> Watch a course Learn object oriented PHP</div>

Here's an example:

Example of a ternary operator in PHP

php
<?php

$age = 30;
$can_vote = ($age >= 18) ? 'yes' : 'no';
echo "Can vote: " . $can_vote;

This will output:

console
Can vote: yes

Note that the ternary operator can only be used for simple statements. If you have a complex set of instructions that you need to execute based on a condition, you will need to use an "if" statement.

Dual-run preview — compare with live Symfony routes.