I am trying to print a table using PHP/HTML. Data stored inside array like this:
Array ( [id] => 1 [first_name] => mike [last_name] => lastname )
My code is as follow. It runs and there are no error however the output is not as expected. Here is the PHP/HTML code:
<table>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
<?php foreach ($res as $item): ?>
<tr>
<td><?php echo $item['id'] ?></td>
<td><?php echo $item['first_name'] ?></td>
<td><?php echo $item['last_name'] ?></td>
</tr>
<?php endforeach; ?>
</table>
The result I get is the first character of the items:
1 2 3
1 1 1
m m m
l l l
Not sure what I am doing wrong? I would really appreciate an explanation.
UPDATE:
PHP CODE that has no errors:
<?php
foreach ($result as $row)
{
echo '<tr>';
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['first_name'] . '</td>';
echo '<td>' . $row['last_name'] . '</td>';
echo '</tr>';
}
?>
And this is my array with only one "row" in it:
Output of $result variable using print_r($result) wrapped with < PRE > tags
Array
(
[id] => 3
[first_name] => Jim
[last_name] => Dude
)
Here is the result I am getting:
Actual Table result:
ID First Name Last Name
3 3 3
J J J
D D D
However if I have 0 in array or more than 1 (meaning 2 or more) it works perfectly. IT JUST DOES NOT WORK WHEN I HAVE ONLY ONE "ROW" OF ELEMENTS INSIDE ARRAY. For example this array, works perfectly:
Array
(
[0] => Array
(
[id] => 3
[first_name] => Jim
[last_name] => Dude
)
[1] => Array
(
[id] => 4
[first_name] => John
[last_name] => Dude2
)
)
I get this result:
ID First Name Last Name
3 Jim Dude
4 John Dude2
I am not really sure what I am doing wrong. The idea is not knowing how many items is in a Table read it into $result
variable and then using this variable print all elements inside HTML table. Table could contain O elements, 1 row of elements, 1 or more rows of elements.