I am trying to print a table using PHP / HTML. The data stored inside the array is as follows:
Array ( [id] => 1 [first_name] => mike [last_name] => lastname )
My code is as follows. It works and there are no errors, but 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>
As a result, I get the first character of the elements:
1 2 3 1 1 1 mmm lll
Not sure what I am doing wrong? I am very grateful for the 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 "string" in it:
Variable $ result output using print_r ($ result) wrapped in <PRE> tags
Array ( [id] => 3 [first_name] => Jim [last_name] => Dude )
Here is the result I get:
Actual result of the table:
ID First Name Last Name 3 3 3 JJJ DDD
However, if I have 0 in the array or more than 1 (which means 2 or more), it works fine. THIS ONLY DOES NOT WORK WHEN I HAVE ONLY ONE "ROW" OF ELEMENTS INSIDE THE MASS. For example, this array works fine:
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'm not quite sure what I'm doing wrong. The idea does not know how many elements in the table read it in the $result variable, and then use this variable to print all the elements inside the HTML table. A table can contain O elements, 1 row of elements, 1 or several rows of elements.