Print highlighted matrix specific values

Asked

Viewed 706 times

2

In my studies here with matrices I’m trying to highlight only the odd values (leave in bold), but I don’t understand how to do this. Below follows what I did, but I am printing both the numbers in bold and the normal ones.

 <?php
 $matriz = array(
     array(50, 35, 44),
     array(25, 11, 32),
     array(53, 95, 78)
 );
 foreach ($matriz as $v1) {
     foreach ($v1 as $v2) {
         echo $v2, ' '; // imprime todos valores com espaço
         if ($v2 & 1) { // se for impar
             echo '<b>', $v2, '</b>';
         }
     }
     echo '<br/>';
 }
 ?>
  • where that came from $v2 & 1 ?

  • 1

    http://stackoverflow.com/questions/600202/understanding-php-ampersand-bitwise-and-operator

  • 1

    Why did they edit my code? It was very well viewed.

  • 1

    phpricardo, I think only the array is visualized better as @Rodrigorigotti did, but really is a matter of taste and opinion. Rodrigo, we should only dream when it’s an amateur posting code spaghetti. If it was my post, I would revert the keys to a new line, because it’s the style I prefer.

  • @brasofilo understood. actually I usually correct the code according to the standards that the PHP-FIG guys are defining, it’s just a stubbornness of mine :)

2 answers

2

To know if a number is for or odd, use the following:

Par:

$numero % 2 == 0

Odd:

$numero % 2 == 1

So it becomes clearer what you mean, in my opinion.

Besides, I wouldn’t use <b> and yes <strong>.

  • That way you can test Miguel too. ;)

  • 1

    Hint of the accepted Strong. D

2


Your problem was a simple logic error when using two echo to print the items, the correct would be the following:

    foreach ($matriz as $v1){
       foreach ($v1 as $v2){
          // eu removi o echo daqui
           if ($v2 & 1) { // se for impar
               echo '<b>', $v2, ' </b>';
           } else {
              echo $v2,' '; // e coloquei ele aqui
           }
       }
       echo '<br/>';
   }

What was wrong was that you first printed out all the items in the array, and then created one if() printing a second time items that were odd, this time in bold. That’s why these items were duplicated.

  • Perfect Kazzkiq, really was doing wrong, still have problems with logic unfortunately. Thank you for the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.