tags:

views:

240

answers:

7

$top += $i ? 12 : 0;

+12  A: 

If $i is

  • set
  • and not false
  • and not null

increment $top by twelve; otherwise, by zero, implicitly turning $top (not $i) into a numeric variable if it isn't one already.

Pekka
In addition, if `$i` is not set, it raises a warning.
R. Bemrose
@R.B good point. To avoid the warning, `(isset($i) and ($i))` should be used instead of `$i`.
Pekka
When $i is turned to a numeric variable, does it get the value 0?What is it about php that causes $i to be implicitly turned into a numeric var? And why is it implicitly changed to be numeric var, as opposed to a boolean (since the ternary operator might suggest a boolean codition)?
Eddified
I still don't see why php expects $i to be an integer... Since the ternary operator is supposed to be similar to:`if ($a) { return $b; } else { return $c; }`Then why in the world does it "need" $i to be an int?
Eddified
@Eddified arrrrrgh, now I see. `$i` is never expected to be an integer and will never be turned into one. *`$top`* will get turned into an integer through the `+0` operation. I put the wrong variable name into the text. Mea culpa, sorry sorry. Corrected and removed my comment.
Pekka
Thanks, makes sense now!
Eddified
+11  A: 

If $i has a value set (not empty/null meaning condition resolves to true), then 12 is added to $top and 0 otherwise.

It is basically shorthand of:

if ($i)
{
  $top += 12;
}
else
{
  $top += 0;
}

This is known as Ternary operator.

Sarfraz
+1 for link to ternary operator.
Pekka
+1: Interesting, never knew about this operator.
+4  A: 

Shorthand for:

if ($i) {
  $top += 12;
}
Matt
Clearest answer.
Mark Byers
you are missing `else` there.
Sarfraz
@Sarfraz is right: If `$i` is not numeric before the operation, the `+0` would make an implicit conversion, so it's not 100% identical (even though in practice, it's probably not relevant as `$i` will probably be numeric). Good answer either way.
Pekka
+2  A: 

If $i is true (e.g., not zero or an empty string), 12 is added to $top. Otherwise, nothing is added to $top.

This is equivalent to

if($i)
    $top = top + 12;
warrenm
+1  A: 

Increase value of $top by 12 if $i has true boolean value (ie. $i = 1, $i = true etc.) or by 0 if not.

http://www.php.net/manual/en/language.operators.assignment.php

Ternary Operaotr

Crozin
A: 

The $i ? 12 : 0 is a "shorthand" if statement. In this case, $i is evaluated as an expression. If the expression evaluates to true, then the value 12 is used as the r-value in the addition-assignment expression. If $i evaluates to false, then 0 is used as the r-value.

Mat