Chunk array into pattern - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of Chunk array into pattern.php

  1. <?php
  2.  
  3. //  The original array
  4. $original = [1,2,3,4,5,6,7,8,9];
  5.  
  6. // The pattern
  7. $pattern = [2,1];
  8.  
  9. // Initialize
  10. $new = [];
  11. $index = 0;
  12.  
  13.  
  14. foreach ($original as $item) {
  15.     
  16.     //  Create array of key does not exist
  17.     if (!array_key_exists($index, $new)) {
  18.         $new[$index] = [];
  19.     }
  20.     
  21.     //  Add the item to the current index
  22.     $new[$index][] = $item;
  23.     
  24.     // If the current index is now full, move onto the next
  25.     if (count($new[$index]) === current($pattern)) {
  26.         $index++;
  27.         
  28.         // Move onto the next aptternb, if it fails, go to the beginning
  29.         if (next($pattern) === false) {
  30.             reset($pattern);
  31.         }
  32.     }
  33. }
  34.  
  35.  
  36. print_r($new);
  37.  
  38.  
  39.  
File Description
  • Chunk array into pattern
  • PHP Code
  • 07 Jan-2021
  • 691 Bytes
You can Share it: