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.
Result of php executing
Full code of Chunk array into pattern.php
- <?php
- // The original array
- $original = [1,2,3,4,5,6,7,8,9];
- // The pattern
- $pattern = [2,1];
- // Initialize
- $new = [];
- $index = 0;
- foreach ($original as $item) {
- // Create array of key does not exist
- if (!array_key_exists($index, $new)) {
- $new[$index] = [];
- }
- // Add the item to the current index
- $new[$index][] = $item;
- // If the current index is now full, move onto the next
- if (count($new[$index]) === current($pattern)) {
- $index++;
- // Move onto the next aptternb, if it fails, go to the beginning
- if (next($pattern) === false) {
- reset($pattern);
- }
- }
- }
- print_r($new);
File Description
- Chunk array into pattern
- PHP Code
- 07 Jan-2021
- 691 Bytes
You can Share it:
Latest PHP Pastes