I need an explanation of what a code I do not understand does

6

I need to make a change to a code and found this: <?=(((++$i % 2) == 1) ? 'class="colored"' : '')?>

What does this code do?

    
asked by anonymous 16.11.2015 / 14:21

3 answers

10

It is a ternary that checks whether $i is an odd number using the two module, if positive returns a html chunk which is the definition of a class (css) from the opposite an empty string is returned. >

The symbol ( <?= ) at the beginning is to print the result of the expression it is equivalent to <?php echo 'algo';

((++$i % 2) == 1) ? 'class="colored"' : '';
 | 1 | 
 |  2           | 3 caso seja impar   | 4 caso seja par

1 - Pre-increment of $i ie it will have its value increased before re-calculating the module.

2 - Calculating the two-case module returns 1 means that the number is odd if zero is even.

3 - Condition true.

4 - False condition.

It is likely that this piece of code has been extracted from something like:

<?php
    $i = 0;
    while($row = mysqli_fetch_assoc($result)){
?>
    <tr <?=(((++$i % 2) == 1) ? 'class="colored"' : '');?>>
        <td><?=$row['nome'];?></td>
        <td><?=$row['descricao'];?></td>
    </tr>

    <?php } ?>
    
16.11.2015 / 14:23
13

It increments the variable $i divide by 2 and takes the rest. If the rest is 1 - if it is odd - it uses string 'class="colored"' , otherwise use an empty string . In case he is assigning the class when the counter is odd, that is, he is probably making a zebra table. But you can not state without further details. If it's not in a loop, this seems to be very wrong.

This is the conditional operator . Along with pre-increment operator .

    
16.11.2015 / 14:24
3

It is in a table that in a row of one color and in the next line of another color and alternating.

    
16.11.2015 / 14:26