How To Use PHP Ternary Operator For If...else Condition Example

03-Apr-2023

.

Admin

How To Use PHP Ternary Operator For If...else Condition Example

Hi guys,

Today i will explained How To Use PHP Ternary Operator For If...else Condition in php. This example is so easy to use in php.

So let's start to the example.

If else condition is used to execute the block of code based on condition. If the given condition is not true then alternative code of block will be executed.

Syntax


if (condition) {

// code to be executed if the given condition is true...

} else {

// code to be executed if the given condition is false...

}

You can see the above condition takes 4 lines of code. So when you have only simple one line statement to be executed in if... else condition, then you use ternary operator.

Ternary operator(shorthand property) is same regular if...else condition in one line.

Syntax

(condition) ? (statement to be executed for true condition) : (statement to be executed for false condition)

Example 1

<?php

$x = 5;

$text = ($x < 10) ? 'variable is x is less than 10' : $text = 'variable x is greater than 10';

echo($text);

Output

variable is x is less than 10

Example 2

<?php

$pass = true;

$result = ($pass) ? 'Passed' : 'Failed';

echo($result);

Output

Passed

This is useful when assiging value to variable in form submit.

Example 2

$first_name = isset($_POST['first_name']) ? $_POST['first_name'] : null;

Now you can check your own.

I hope it can help you...

#PHP 8

#PHP