0

as title says I wanna chunk an array by three and display results each in a single row.

In JS no problems:

const array = [1,2,3,4,5,6,7];
let i, arr, j;

for (i = 0; i < array.length; i += 3) {

 arr = array.slice(i, i + 3);
 let div = document.createElement("div");
 div.classList.add('row');

 for (j = 0; j < arr.length; j++) {
  let par = document.createElement("p");
  let res = document.createTextNode(arr[j]);
  par.appendChild(res);
  div.appendChild(par);
 }

document.body.appendChild(div);

}

Getting correctly:

<div class="row">
 <p>1</p>
 <p>2</p>
 <p>3</p>
</div>
<div class="row">
 <p>4</p>
 <p>5</p>
 <p>6</p>
</div>
<div class="row">
 <p>7</p>
</div>

In PHP, with this:

<?php
  $array = [1,2,3,4,5,6,7];
  for ($i = 0; $i < count($array); $i += 3) :
    $arr = array_slice($array, $i, $i + 3);
?>

  <div class="row">
    <?= implode(" ", $arr); ?>
  </div>

<?php endfor; ?>

I get:

<div class="row">
 <p>1</p>
 <p>2</p>
 <p>3</p>
</div>
<div class="row">
 <p>4</p>
 <p>5</p>
 <p>6</p>
 <p>7</p>
</div>
<div class="row">
 <p>7</p>
</div>

I always get the middle row wrong (even if you increase $array), what am I missing? :/

0

5 Answers 5

2

The third parameter of array_slice() is the length and not the end point, so change it to...

$arr = array_slice($array, $i, 3);
Sign up to request clarification or add additional context in comments.

Comments

1

The arguments to array_slice in PHP and slice in JS aren't quite the same. PHP takes a start and a length, whereas JS takes a start and an end.

PHP:

array_slice(array $array, int $offset, int $length = NULL);

JS:

arr.slice(begin, end)

So you can't quite just copy the implementation over from one to the other. If you change your PHP line to:

$arr = array_slice($array, $i, 3);

(just specifying the length 3 instead of $i + 3), then it should work correctly.

Alternatively in PHP, you could just use array_chunk, and loop over the resulting chunks.

Comments

1

You may use array_chunk() in php

<?php
$array = [1,2,3,4,5,6,7];
echo "<pre>";
print_r(array_chunk($array, 3));

?>

Comments

1

There's already array_chunk function:

$chunks = array_chunk($array, 3);
foreach ($chunks as $chunk) {?>
    <div class="row">
        <?= implode(" ", $chunk); ?>
    </div>
<?php
}

Comments

0

Use array_chunk().

$array = [1,2,3,4,5,6,7];
$chunks = array_chunk($array, 3);

foreach ($chunks as $chunk) {
  // Do whatever you want with chunks: e.g.:
  implode(" ", $chunk);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.