Reputation:
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>
Upvotes: 1
Views: 2609
Reputation: 1
Remove the key increment as it will increment the last character of the key. I'm not sure why this happens, in any case, it's only applicable in a for loop and redundant in a foreach
Upvotes: 0
Reputation: 76646
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>
Upvotes: 1