Php array chunk
From w3cyberlearnings
Contents |
PHP function array_chunk
This function splits an array into chunks for a new array
Syntax array_chunk
- array: array input
- size: size to split
- preserve_key: true (preserve the key as the origional array), false (default, not reserve)
array_chunk(array, size, preserve_key);
Example 1
<?php $person = array('John', 'Marry', 'Bob', 'Lucous', 'Chris', 'Paul'); print_r(array_chunk($person, 2)); ?>
Output
Array ( [0] => Array ( [0] => John [1] => Marry ) [1] => Array ( [0] => Bob [1] => Lucous ) [2] => Array ( [0] => Chris [1] => Paul ) )
Example 2: Preserve key
<?php $person = array('John'=>30, 'Marry'=>80, 'Bob'=>80, 'Lucous'=>30, 'Chris'=>29, 'Paul'=>93); print_r(array_chunk($person, 2,true)); ?>
Output
Array ( [0] => Array ( [John] => 30 [Marry] => 80 ) [1] => Array ( [Bob] => 80 [Lucous] => 30 ) [2] => Array ( [Chris] => 29 [Paul] => 93 ) )
Example 3
<?php $person = array('John'=>30, 'Marry'=>80, 'Bob'=>80, 'Lucous'=>30, 'Chris'=>29, 'Paul'=>93); print_r(array_chunk($person, 2)); ?>
Output
Array ( [0] => Array ( [0] => 30 [1] => 80 ) [1] => Array ( [0] => 80 [1] => 30 ) [2] => Array ( [0] => 29 [1] => 93 ) )
Related Links
- array_change_key_case
- array_chunk
- array_combine
- array_count_values
- array_diff_assoc
- array_diff_key
- array_diff_uassoc
- array_diff_ukey
- array_diff
- array_fill_keys
- array_fill
- array_filter
- array_flip
- array_intersect_assoc
- array_intersect_key
- array_intersect_uassoc
- array_intersect_ukey
- array_intersect
- array_key_ exists
- array_keys