array_chunk
-
This function’s solution will only work within the context of the Rails framework.
We can split an array into separate chunks in Rails using the
Array#in_groups_ofmethod.PHP
$animals = array('ant', 'bat', 'cat', 'dog', 'elk'); $result = array_chunk($animals, 3); var_export($result); // => array(0 => array(0 => 'ant', 1 => 'bat', 2 => 'cat'), // 1 => array(0 => 'dog', 1 => 'elk'))
The default Rails implementation of
in_groups_ofwill fill any missing elements withnil.Rails
animals = ["ant", "bat", "cat", "dog", "elk"] p animals.in_groups_of(3) # => [["ant", "bat", "cat"], ["dog", "elk", nil]]
To get the same results as our PHP version, we need to pass
falseas the second argument toin_groups_of.Rails
animals = ["ant", "bat", "cat", "dog", "elk"] p animals.in_groups_of(3, false) # => [["ant", "bat", "cat"], ["dog", "elk"]]
Looking for Rails or PHP web application development, integration, and training?
Rails for PHP is brought to you by Maintainable Software. Get custom web applications and personalized training from the authors of the book and website.

