Home > Back-end >  How to display my 2D array values into a table in php using a for loop
How to display my 2D array values into a table in php using a for loop

Time:05-30

$operatingsystems = array(
        array("Mac", "Windows", "Linux"),
        array("Apple", "Microsoft", "Linus Torvalds"),
        array("Closed Source", "Closed Source", "Open Source"));

Above is my array- I'm having trouble putting into a table using a for loop on php, Been practicing code by my self & I'm stuck on this- any help would be appreciated!!

CodePudding user response:

Try to use foreach, it is way easier to display any multi-dimensional array with it like this:

/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2\n";
    }
}

CodePudding user response:

public function     displayTable()
{
$disp = '<table     >';
foreach ($this->operatingsystems as $tr) 
{
$disp .= '<tr>';
foreach ($tr as $td)
{
$disp .= '<td>' . $td . '</td>';
}
$disp .= '</tr>';
}
$disp .= '</table>';
echo $disp;
}
  • Related