1

Ok so I have an array full of values and I want to echo them in a specific way.

This is my code so far:

<?php foreach( $names as $i ) {
  echo $i."<br>";
}?>

So at the moment I am stacking each value under one another. But I want to change it into columns.

I want it to display like this:

Name 1 Name 2

Name 3 Name 4

And so on... How can I achieve this?

1
  • Providing a sample of what's in your array would be helpful. Also be clear about how you determine the number of columns. Commented Feb 15, 2020 at 18:22

1 Answer 1

1

Iterate through your array and build a HTML form from it. Since you'd like 2 rows, here is an example:

<?php if($names) :
    echo '<table>';
    $counter = 1;
    foreach($names as $i) :
        if($counter%2 !== 0) {
            // Start new row
            echo '<tr>';
        }
        echo '<td>' . $i . '</td>';
        if($counter%2 == 0) {
            // End row
            echo '</tr>';
        }
        $counter++;
    endforeach;
    if($counter%2 == 0) {
        // Last empty cell
        echo '<td></td></tr>';
    }
    echo '</table>';
endif;
?>

Demo: https://3v4l.org/knGae

Sign up to request clarification or add additional context in comments.

4 Comments

I will test this and let you know if it works. Thanks for your input.
that seems to be nearly the exact outcome as I want. 2 more questions if you don't mind. How can I separate them away from eachother? As columns seem very tightly close to each other at the moment. Secondly can you explain what you are doing with the $counter variable and what is %2 mean? Thanks so much
Sure, no problem. For styling, I recommend using simple CSS to add padding or some border to your table cells, check here: w3schools.com/css/css_table.asp | As for the % in PHP, it's the remainder operator. If the counter is divisible by 2 (%2 == 0), that means its an even value, so the loop closes the table row. If it's not divisible by 2 (%2 !== 0), then it's an odd value, so the loop opens the table row. After the loop, if there were an odd number of elements, it adds the last empty cell, and closes the open row. Hope I explained that well, you can find more examples below:

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.