0

I was doing a simple PHP array table, but the result of my code is not what I've expected,

<?php 
    $names = array (
        'First Name' => 
            array('Alfre', 'Beka', 'Charlie'),
        'Middle Name' =>
            array('Brom', 'Tiv', 'Clore'),
        'Last Name' =>
            array('Adani', 'Filial', 'Chrome'),
    );
    
    echo '<table border="1">';
    foreach($names as $name => $indv_name) {
                echo '<tr>';
                echo "<th>$name</th>";
                foreach($indv_name as $per_name) {
                    echo '<td>',$song, '</td>';
                }
                echo '</tr>';
            }
    echo '</table>';
    ?>

The result of the array of this code is echoed horizontally, can anyone help me to echo it vertically?

Here's my output example:

firstname -> value, value, value
middlename -> value, value, value
lastname -> value, value, value

Output that I want to expect:

firstname - middlename - lastname
  value   -   value    -  value
  value   -   value    -  value
  value   -   value    -  value
          -   value    -  value
                       -  value

And whenever I add value in the array, it won't break the line. Sorry for the late edit

4
  • Please show an example of the result you're expecting and then what you're getting. Commented Apr 16, 2022 at 9:30
  • It would make more sense to organize the array by grouping by the person themself rather than the name type. i.e. 'Alfre' => ['First Name' => 'Alfre', 'Middle Name' => 'Brom', 'Last Name' => 'Adani'] Commented Apr 16, 2022 at 9:31
  • I've already edited my question, to make it more understandable, sorry for late edit Commented Apr 17, 2022 at 1:04
  • you can use display:flex intead table Commented Apr 17, 2022 at 10:05

1 Answer 1

1

A basic way

$names = array (
        'First Name' => 
            array('Alfre', 'Beka', 'Charlie'),
        'Middle Name' =>
            array('Brom', 'Tiv', 'Clore'),
        'Last Name' =>
            array('Adani', 'Filial', 'Chrome'),
);
echo "<table>";
echo "<thead>";
echo "<tr>";
foreach ($names as $key => $value) {
        echo "<th>$key</th>";
    }
    echo "</tr>";
    echo "</thead>";
    echo "<tbody>";
    foreach ($names as $key => $value) {
        echo "<tr>";
        foreach ($value as $key => $value) {
            echo "<td>$value</td>";
        }
        echo "</tr>";
}
echo "</tbody>";
echo "</table>";
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer, but whenever I add value in array, it won't add vertically but on horizontally.
It still lack for vertical allignment of every value in each variable whenever I add another value~

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.