LMayday LMayday - 1 month ago 10
HTML Question

Display a table of the array keys and values in PHP

Just wondering is there any way to display a numerically indexed array in a table format with the array keys and values?

I try to do the following code, but it doesn't work.

<body>
<?php
$countries=array("United State","Canada","England","Russia","Japan");
?>
<h2>Country List</h2>
<?php
echo "<td>".(array_keys($countries,"United State"))."</td><td>".(array_values($countries))."</td>";
?>
</body>

Answer

You don't need any array functions to achieve this. A foreach loop is all that's needed. Here's an improved version of your code with table styling too:

<head>
    <style type="text/css">
        table {
            border-collapse: collapse;
            border: 1px solid black;
        }
        table td,th {
            border: 1px solid black;
        }
        td {
            text-align: center;
        }
    </style>
</head>

<body>

    <?php

    $countries = array(
        "United States",
        "Canada",
        "England",
        "Russia",
        "Japan"
    );

    ?>

    <h2>Country List</h2>

    <table>
        <th>SI No.</th>
        <th>Country Name</th>

        <?php

        foreach ($countries as $key => $value) {
            echo "<tr>";
            echo "<td>" . ++$key . "</td>\n<td>" . $value . "</td>";
            echo "</tr>";
        }

        ?>
    </table>
</body>

Working demo