Skip to content

Instantly share code, notes, and snippets.

@betweenbrain
Created July 16, 2014 05:50
Show Gist options
  • Save betweenbrain/345717521043698f31ba to your computer and use it in GitHub Desktop.
Save betweenbrain/345717521043698f31ba to your computer and use it in GitHub Desktop.
PHP Split Array Into Somewhat Even Groups
<?php
/**
* File index.php
* Created 7/16/14 1:34 AM
* Author Matt Thomas | [email protected] | http://betweenbrain.com
* Support https://github.com/betweenbrain/
* Copyright Copyright (C) 2014 betweenbrain llc. All Rights Reserved.
* License GNU GPL v2 or later
*/
$alphabet = array(
'A' => 'Alpha',
'B' => 'Bravo',
'C' => 'Charlie',
'D' => 'Delta',
'E' => 'Echo',
'F' => 'Foxtrot',
'G' => 'Golf',
'H' => 'Hotel',
'I' => 'India',
'J' => 'Juliet',
'K' => 'Kilo',
'L' => 'Lima',
'M' => 'Mike',
'N' => 'November',
'O' => 'Oscar',
'P' => 'Papa',
'Q' => 'Quebec',
'R' => 'Romeo',
'S' => 'Sierra',
'T' => 'Tango',
'U' => 'Uniform',
'V' => 'Victor',
'W' => 'Whiskey',
'X' => 'X-ray',
'Y' => 'Yankee',
'Z' => 'Zulu',
);
// Number of groups to create
$splits = 3;
// Calculate divisor for fmod based grouping
$divisor = ceil(count($alphabet) / $splits);
// Zero counter for calculating splits
$index = 0;
echo '<ul>';
foreach ($alphabet as $key => $value)
{
$index++;
echo '<li>' . $index . ' ' . $value . '</li>';
// Check if a split is needed
if ($index > 0 && fmod($index, $divisor) == 0)
{
echo '</ul><ul>';
}
}
echo '</ul>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment