-4
    $odd= true;
echo ($odd == true) ? '<tr class="odd_row">' : '<tr class="even_row">';
    $odd = !$odd; 

Please Can Any One Explain this code?

Samir Paruthi
  • 121
  • 1
  • 3
  • 12

3 Answers3

10

The expression [a] ? [b] : [c] is called ternary operator. It is the same as this function:

function ternary($a, $b, $c) {
  if ($a)
    return $b;
  else
    return $c;
}

except that the arguments to the ternary operator are lazy evaluated (i.e. only one of [b] and [c] is actually executed).

$odd = !$odd toggles the value of $odd between true and false.

The code is probably used inside a loop that prints table rows that alternatingly have classes odd_row and even_row, which can then be styled differently using CSS.

Oswald
  • 31,254
  • 3
  • 43
  • 68
3

This means

if ($odd == true){
    echo '<tr class="odd_row">';
}else{
    echo '<tr class="even_row">';
}

and is called ternary operator

Then by $odd = !$odd; the value of this variable is "flipped". I guess it's done to make the next row to be "even".

k102
  • 7,861
  • 7
  • 49
  • 69
0

This is setting the $odd variable to boolean value true

$odd= true;

This uses whats called a terniary operator to print out a string. If $odd is true it will print the first bit, if not then the second. As you have set $odd to true immediately before, it will always print the first bit

echo ($odd == true) ? '<tr class="odd_row">' : '<tr class="even_row">';

This sets $odd to ! (not) $odd so reverses the boolean to false $odd = !$odd;

Sorry for the literal explanation, but I wanted to be thorough

fullybaked
  • 4,117
  • 1
  • 24
  • 37