Problem understanding the following lines

#1

Hello!

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?

#2

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

it’s called a ternary statement.

#3

The manual has a list of operators

php.net/operators

1 Like
#4

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

#5

Thank you so much for the reply!

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

#6

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

2 Likes
#7

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.