I'm trying to write a function that that returns an table from an array. But, for some reason, it is only displaying the first row or the array instead of all.

<html>
<link rel="stylesheet" type="text/css" href="week13.css" />
</head>
<body>
<h2>table</h2>
<br>
<br>
<?php
$table = array("440" => "cubic inch engine","truck F" => 150);
echo ("<table border='1'>\n");
function t6($table)
{
        foreach ($table as $key => $value)
        return ("<tr><td>$key</td><td>$value</td></tr>\n");
}
echo t6($table);
echo "</table>";
?>
<br>
</body>
</html>

This is because you have a return statement within a foreach loop so the loop gets executed only once. Try this way:

function t6($table)
{
    $rows = '';

    foreach ($table as $key => $value) {

        $rows .= "<tr><td>$key</td><td>$value</td></tr>\n";
    }

    return $rows;
}

That worked perfectly. Thank you so much!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.