Here is the code:

$arr = ["Ceylon", "Fish", "Apple", "MongoDB", "123456789990"]; usort($arr,function($a, $b){ return strlen($b)||strlen($a); }); $arr2 = array_slice($arr, 0, 2); echo join(", ",$arr2); 

If in the array_slice($arr, 0, 2); method array_slice($arr, 0, 2); specify the values ​​2 will output 123456789990, MongoDB and if we specify array_slice($arr, 0, 5); it will output 123456789990, MongoDB, Fish, Apple, Ceylon all 5 values ​​of the array, I need to display only the longest values ​​of the array, or vice versa, the shortest, help solve the problem, I'm new to PHP.

    2 answers 2

    ... I need to display only the longest values ​​of the array, or the shortest short order ...

    That is not clear which word is considered long, and which is short, 'test' is long or short, krch will give examples, choose yourself:

    For example, there is an array:

    $ array = ["Ceylon", "Fish", "Apple", "MongoDB", "Seven77"];


    1) Sort by number of characters:

     usort($array, function ($a, $b) { return mb_strlen($b) - mb_strlen($a); }); var_dump($array); 

    Result:

     array(5) { [0] => string(7) "MongoDB" [1] => string(7) "Seven77" [2] => string(6) "Ceylon" [3] => string(5) "Apple" [4] => string(4) "Fish" } 

    2) Only those values ​​whose length is greater than or equal to $length = 5 :

     $result = []; $length = 5; foreach ($array as $key => $value) { if ($length <= mb_strlen($value)) { $result[] = $value; } } var_dump($result); 

    Result:

     array(4) { [0] => string(6) "Ceylon" [1] => string(5) "Apple" [2] => string(7) "MongoDB" [3] => string(7) "Seven77" } 

    3) Find the maximum length, and select the elements with this length:

     $result = []; $length = 0; array_map(function($v) use (&$length) { if ($length < mb_strlen($v)) { $length = mb_strlen($v); } }, $array); foreach ($array as $key => $value) { if ($length == mb_strlen($value)) { $result[] = $value; } } var_dump($result); 

    Result:

     array(2) { [0] => string(7) "MongoDB" [1] => string(7) "Seven77" } 

    • THANK YOU HERE. I UNDERSTAND MORE - Sad
     usort($arr,function($a, $b){ return (strlen($a)==strlen($b)? 0 : (strlen($a)<strlen($b)? 1: -1)); }); 

    Then output the required number of elements from the beginning of the array =) the longest at the beginning, short at the end.

    • I need that she even removed the short, or vice versa. - Sad
    • @ Dreamto createVisualRuby What does short mean? is it 1 character long? or 10? or 1000? - Vladimir Klykov
    • @ Vladimir Klykov well короткие , that is not clear, then: D - Manitikyl
    • $ arr = ["Fi", "Apple", "1"]; short $ arr = ["Ceylon12", "MongoDB", "123456789990"]; Long - Sad
    • @ Dream to create VisualRuby how did you determine that Apple short and MongoDB is long? there was some sort of criterion. why don't we tell him? - Manitikyl pm