Problem understanding the following lines



I ran into the following two lines:

$n = $a < 0 ? 0 : $a;
$m = $b >= count($arr) ? count($arr) - 1 : $b;

How exactly do I read this? What does the <, ? and : on each line mean? How are $n and $m, being calculated?


n = $a < 0 ? 0 : $a;
n = (is the value of $a less than 0? True : False)

it’s called a ternary statement.


The manual has a list of operators

1 Like

This is a ternary. It seems to be a simplified if statement.
I’m still new to PHP, but I’ll try to explain it as succinctly as I can.

$n = if this condition is true ($a < 0) ? return this value (0) : if it is false, return this value ($a)

I read this as:
$m = if the value of $b is greater or equal to count($arr) ? return the value of count($arr) and reduce by 1 : if it is false, return the value of $b


Thank you so much for the reply!

This will surely simplify the code and make life easier(by reducing the amount of if-s).


This is why you don’t name variables $a, $b, $n, $m or $arr… :stuck_out_tongue:


I don’t think you understand if you are saying it will reduce the number of if statements. They are if statements for one thing.