0

I'm trying to break a PHP array of 9 array items into 3 divs. My array is displayed as:

$array = array("item 1", "item 2", "item 3", "item 4", "item 5", "item 6", "item 7", "item 8", "item 9")

This might be a previously asked question but I couldn't find a working solution. I tried what I saw on a similar question here on Break PHP array into 3 columns but it didn't achieve it as I wanted.

The snippet of what I want to achieve is below...

.wrapper {
  display: flex;
  flex-direction: colum;
  gap: 80px;
}

.wrapper div {
  display: flex;
  flex-direction: column;
}
<div class="wrapper">
  <div>
    <p>Item 1</p>
    <p>Item 4</p>
    <p>Item 7</p>
  </div>
  <div>
    <p>Item 2</p>
    <p>Item 5</p>
    <p>Item 8</p>
  </div>
  <div>
    <p>Item 3</p>
    <p>Item 6</p>
    <p>Item 9</p>
  </div>
</div>

2

1 Answer 1

2

If I understood you correctly, maybe this solution will work for you:

<?php 
  $data = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6', 'Item 7', 'Item 8', 'Item 9'];
  $columnLimit = 3;
  $columns = array_fill(0, $columnLimit, []);
   
  foreach ($data as $key => $value) {
    $columns[$key % $columnLimit][] = $value;
  };
?>


<div class="wrapper">
  <?php foreach ($columns as $column): ?>
  <div>    
    <?php foreach($column as $item): ?>
      <p><?=$item?></p>
    <?php endforeach; ?>
  </div>
  <?php endforeach; ?>
</div>

A working example can be seen here: https://onlinephp.io/c/bd015

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

4 Comments

array_fill and the foreach can be replaced by: $columns = array_chunk($data, $columnLimit);
@lukas.j array_chunk is not suitable because it splits the array sequentially, i.e. [['Item 1, 'Item 2', 'Item3'], ['Item 4', 'Item 5', 'Item 6'], ['Item 7', 'Item 8', 'Item 9']], but we need to distribute the elements as they are fill evenly, i.e. [['Item 1, 'Item 4', 'Item7'], ['Item 2', 'Item 5', 'Item 8'], ['Item 3', 'Item 6', 'Item 9']].
You are of course right. I did not read the question properly. Sorry for that.
array_chunk() can be an appropriate component of a solution; its data just needs to be transposed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.