Group By Alphabets Using Range in Array Php
Here is a simple example to group array values by alphabet range.
For example
$arr=array(aaa, aab, aac, aad, aae, aba, abb, abc, abd, abe, aca, acb, acc, acd, ace, ada, adb, adc, add, ade, aea, aeb, aec, aed, aee, baa, bab, bac, bad, bae, bba, bbb, bbc, bbd, bbe, bca, bcb, bcc, bcd, bce, bda, bdb, bdc, bdd, bde, bea, beb, bec, bed, bee, caa, cab, cac, cad, cae, cba, cbb, cbc, cbd, cbe, cca, ccb, ccc, ccd, cce, cda, cdb, cdc, cdd, cde, cea, ceb, cec, ced, cee, daa, dab, dac, dad, dae, dba, dbb, dbc, dbd, dbe, dca, dcb, dcc, dcd, dce, dda, ddb, ddc, ddd, dde, dea, deb, dec, ded, dee, eaa, eab, eac, ead, eae, eba, ebb, ebc, ebd, ebe, eca, ecb, ecc, ecd, ece, eda, edb, edc, edd, ede, eea, eeb, eec, eed, eee);
We can group the array values starting with A and B , C and D ,E and F as an array like .
Array
(
[A-B] => Array
(
[0] => aaa
[1] => aab
[2] => aac
[3] => aad
[4] => aae
[5] => aba
[6] => abb
[7] => abc
[8] => abd
[9] => abe
[10] => aca
[11] => acb
[12] => acc
[13] => acd
[14] => ace
[15] => ada
[16] => adb
[17] => adc
[18] => add
[19] => ade
[20] => aea
[21] => aeb
[22] => aec
[23] => aed
[24] => aee
[25] => baa
[26] => bab
[27] => bac
[28] => bad
[29] => bae
[30] => bba
[31] => bbb
[32] => bbc
[33] => bbd
[34] => bbe
[35] => bca
[36] => bcb
[37] => bcc
[38] => bcd
[39] => bce
[40] => bda
[41] => bdb
[42] => bdc
[43] => bdd
[44] => bde
[45] => bea
[46] => beb
[47] => bec
[48] => bed
[49] => bee
)
[C-D] => Array
(
[0] => caa
[1] => cab
[2] => cac
[3] => cad
[4] => cae
[5] => cba
[6] => cbb
[7] => cbc
[8] => cbd
[9] => cbe
[10] => cca
[11] => ccb
[12] => ccc
[13] => ccd
[14] => cce
[15] => cda
[16] => cdb
[17] => cdc
[18] => cdd
[19] => cde
[20] => cea
[21] => ceb
[22] => cec
[23] => ced
[24] => cee
[25] => daa
[26] => dab
[27] => dac
[28] => dad
[29] => dae
[30] => dba
[31] => dbb
[32] => dbc
[33] => dbd
[34] => dbe
[35] => dca
[36] => dcb
[37] => dcc
[38] => dcd
[39] => dce
[40] => dda
[41] => ddb
[42] => ddc
[43] => ddd
[44] => dde
[45] => dea
[46] => deb
[47] => dec
[48] => ded
[49] => dee
)
[E-F] => Array
(
[0] => eaa
[1] => eab
[2] => eac
[3] => ead
[4] => eae
[5] => eba
[6] => ebb
[7] => ebc
[8] => ebd
[9] => ebe
[10] => eca
[11] => ecb
[12] => ecc
[13] => ecd
[14] => ece
[15] => eda
[16] => edb
[17] => edc
[18] => edd
[19] => ede
[20] => eea
[21] => eeb
[22] => eec
[23] => eed
[24] => eee
)
)
Use the following Php code
PHP Code
$ranges=array(
'A-B'=>range('A','B'),
'C-D'=>range('C','D'),
'E-F'=>range('E','F') // you can extend the range by adding the range( ) function
);
$final=array();
foreach ($arr as $item) {
$first_letter=strtoupper(substr($item[0],0,1));
foreach ($ranges as $label => $range) {
if (in_array($first_letter,$range)) {
$final[$label][]=$item;
break;
}
}
}
$alpharange = array_keys($ranges);
// output the final array
echo"
".print_r($final,true)."
";