Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

php – how to generate new <tr> after fourth iteration from 2 arrays and display them in alternate order?

i have 2 arrays:

$arr1= [‘A’,’B’,’C’];

$arr2=[1, 2, 3];

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

what i want to achieve is something like this:

-----------------
| A | A | A | A |
-----------------
| 1 | 1 | 1 | 1 |
-----------------
| B | B | B | B |
-----------------
| 2 | 2 | 2 | 2 |
-----------------
| C | C | C | C |
-----------------
| 3 | 3 | 3 | 3 |
-----------------

and this is what i’ve tried:
`

<?php
$arr1= ['A','B','C'];
$arr2=[1, 2, 3];
$combine = array_combine($arr1, $arr2);

echo "<table>\n";
foreach ( $combine as $i => $a) {
    echo "<tr>\n";
    for ($j=0; $j < 4 ; $j++) { 
  if ( $a % 4 == 0) {
    echo "</tr>\n  <tr>\n";
  }
  echo "<th>$i</th>\n";
  echo "<td>$a</td>\n";
  }
  echo "</tr>\n";
}

echo "</table>\n";

?>

`

the result isn’t like what i’m expecting.

enter image description here

any help will be greatly appreciated.

>Solution :

No need of nested for loops or any % 4. Access the value from the second array using the key from the foreach iteration of the first array since both arrays are symmetrical in size and type. Use str_repeat 4 times to print the value 4 times as required.

<?php

$arr1 = ['a','b','c'];
$arr2 = [1, 2, 3];

echo "<table>";
foreach ( $arr1 as $key => $value) {
  echo "<tr>" , str_repeat("<td>$value</td>", 4) , "</tr>";
  echo "<tr>" , str_repeat("<td>$arr2[$key]</td>", 4) , "</tr>";
}

echo "</table>";

Online Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading