If I have an array of 20 elements, I would like to know if there is a way to traverse it in such a way that it shows 5 rows of four columns on the screen? Thanks ...
If I have an array of 20 elements, I would like to know if there is a way to traverse it in such a way that it shows 5 rows of four columns on the screen? Thanks ...
It can be done in a thousand ways, this one:
<?php
$elementos = array(
array("nombre" => "Pepe", "edad" => "20"),
array("nombre" => "Carmen", "edad" => "21"),
array("nombre" => "Sofía", "edad" => "20"),
array("nombre" => "Jose", "edad" => "21"),
array("nombre" => "Raul", "edad" => "22"),
array("nombre" => "Elena", "edad" => "22"),
array("nombre" => "Carlos", "edad" => "25"),
array("nombre" => "Ramón", "edad" => "19"),
array("nombre" => "Silvia", "edad" => "20"),
array("nombre" => "Raquel", "edad" => "20"),
array("nombre" => "Sergio", "edad" => "23"),
array("nombre" => "Sandra", "edad" => "22"),
array("nombre" => "Pedro", "edad" => "20"),
array("nombre" => "Mirella", "edad" => "21"),
array("nombre" => "Clara", "edad" => "20"),
array("nombre" => "Toni", "edad" => "23"),
array("nombre" => "Ferrán", "edad" => "22"),
array("nombre" => "Montse", "edad" => "22"),
array("nombre" => "Pilar", "edad" => "21"),
array("nombre" => "Francisca", "edad" => "19")
);
$cols = 4;
$i = 0;
echo "<table>";
foreach($elementos as $el) {
if($cols == $i) $i = 0; // Nueva fila, comenzar de nuevo
if($i == 0) { // Es nueva fila, pintar tr
echo "<tr>";
}
echo "<td>" . $el["nombre"] . " (" . $el["edad"] . ")</td>"; // El valor
if($cols == $i) { // Cerrar nueva fila
echo "</tr>";
}
$i++;
}
echo "</table>";
?>