hakkikonu hakkikonu - 1 month ago 10
PHP Question

How to group a PHP array by its elements length?

I have an array like:-

array("a","b","ab","xy","abc","xyz","abcd","abcde");


I want to group this array by value's length. So it should be like:-

array(
"1" => array("a","b"), //because there are two value which their lengths are = 1
"2" => array("ab","xy"),
"3" => array("abc","xyz"),
"4" => array("abcd"),
"5" => array("abcde")
);


Than I want to reverse order by index;

Final output should;

array(
"13" => array("13 length char"),
"12" => array("12 length char"),
...
...
"5" => array("abcde"),
"4" => array("abcd"),
"3" => array("abc","xyz"),
"2" => array("ab","xy"),
"1" => array("a","b")
);


After I used
krsort()
output is

Array(
[10] => Array
(
[0] => Abdülbari
)

[8] => Array
(
[0] => ablefari
)

[7] => Array
(
[0] => arakari
)

[3] => Array
(
[0] => ari
)

[14] => Array
(
[0] => ağari beğari
)

[20] => Array
(
[0] => ağır erkeli muzari
)

[12] => Array
(
[0] => Amerikanvari
[1] => amudufıkari
)

[5] => Array
(
[0] => abari
[1] => abari
[2] => Acari
[3] => apari
[4] => atari
)

[6] => Array
(
[0] => abbari
[1] => antari
[2] => asgari
[3] => asgari
[4] => aşari
)

)


Array index should ordered from bigger index to lower index like: 20,14,12..

Answer

You can do it like below:-

<?php

$array = array("a","b","ab","xy","abc","xyz","abcd","abcde");

$final_array = array();
foreach ($array as $arr){
   $final_array[strlen( $arr)][] =  $arr;  //I have checked the  length of values and make it the key so that automatically your each value will go to corresponding length array
}

echo "<pre/>";print_r($final_array);

Output:- https://eval.in/671126

Note:- I have checked the length of values and make it the key so that automatically your each value will go to corresponding length array

final output what you want:- https://eval.in/671137