Understanding PHP's ternary operator

Guessed

I understand whiles, ifs, fors, cases, arrays, functions, and other syntactic constructs and my coding experience is 70’s style Fortran and T-SQL.

Now I’m trying to understand PHP, but it occasionally seems to compress several statements into one obfuscating line of code. What’s the expanded equivalent of the following single line of PHP below?

$start = gt("start") === false ? 0 : intval(gt("start"));
Amal Murali

It is a ternary operator. They're usually of the following format:

expr1 ? expr2 : expr3;

Which means:

if expr1 then return expr2 otherwise return expr3

It can be visualized as follows:

Your code can be rewritten as:

if (gt("start") === false) {
    $start = 0;
} else {
    $start = intval(gt("start"));
}

It can improved as follows, to avoid an extra function call:

if (($result = gt("start")) === false) {
    $start = 0;
} else {
    $start = intval($result);
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Understanding PHP's ternary operator

From Dev

understanding Complex inArray ternary operator

From Dev

understading the ternary operator in php

From Dev

evaluation of ternary operator in php

From Dev

Ternary Operator in PHP

From Dev

PHP Ternary Operator Misunderstanding?

From Dev

evaluation of ternary operator in php

From Java

How to write a PHP ternary operator

From Dev

PHP ternary operator syntax error

From Dev

ternary operator in php with echo value

From Dev

PHP ternary operator syntax error

From Dev

Conditional ternary operator malfunctions (PHP)

From Dev

Ternary operator inside calculation PHP

From Dev

Ternary operator in PHP generated table

From Dev

What's result of this ternary operator?

From Java

PHP ternary operator vs null coalescing operator

From Dev

understanding ternary operator in jquery `show` and `hide` method.

From Dev

How to use continue keyword in a ternary operator in php

From Dev

convert some lines of php statement into ternary operator

From Dev

Is there a PHP like short version of the ternary operator in Java?

From Dev

Implement inline ternary operator in embedded HTML in PHP

From Dev

How to use php ternary operator in the parameter of a function?

From Dev

How to use continue keyword in a ternary operator in php

From Dev

PHP selected dynamic option with Ternary Operator

From Dev

convert some lines of php statement into ternary operator

From Dev

Can logical operator be used with in ternary operators in PHP

From Dev

PHP inline statement using ternary logic operator "?:"

From Dev

Using Ruby's ternary operator ? : to shorten this

From Dev

Ternary operator in CMake's generator expressions

Related Related

HotTag

Archive