0

How can I chunk an array in new arrays starting with each word of the original array? So the first word of each array should be the second word of the previous array.

for example

$list(1=>we, 2=>have, 3=>a, 4=>good, 5=>day);

Using array_chunk would give as new arrays (we, have), (a, good), (day, and) and so on.. But I want

$newList(0=>(we, have), 1=>(have, a), 2=>(a, good), 3=>(good, day));

2 Answers 2

3
for ($i = 0; $i < count($list) - 2; $i++) {
  $newList[] = array($list[$i], $list[$i+1]);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Another way:

<?php        
foreach ($list as $key => $word) {
    if ($key < count($list) - 1) $newlist[$key][]   = $word;
    if ($key > 0)                $newlist[$key-1][] = $word;
}
?>

Comments

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.