I try to do it, but it does not give me the desired result.

2.html

<form action="2.php" method="post"> <textarea name="a"></textarea> <input type="submit" value="Submit"> </form> 

2.php

 $a = $_POST ['a']; include '2.html'; function getTop3($a) { $a = explode(' ', $a); for ($i=0; $i<count($a); $i++) { if(mb_strlen($a[$i]) > mb_strlen($a[$i+1])) { $a[$i] = $a[$i+1]; } } return (array_slice($a, 0, 3)); } print_r(getTop3($a)); 

    3 answers 3

    Need something like that?

     <?php $words_text = 'aaa bbbbb cc ddddddddddddd eee'; $words = explode(' ', $words_text); print_r(topThree($words)); function topThree($words){ usort($words, 'cmp'); return array_slice($words, count($words) - 3, 3); } function cmp($a, $b){ if( strlen($a) == strlen($b) ) return 0; if (strlen($a) > strlen($b) ) return 1; else return -1; } 
    • that's just not clear the expression count ($ words) - 3 in array_slice ($ words, count ($ words) - 3, 3); Can you characterize? - Beginner
    • Those. Why count ($ words) is 3, not count ($ words) - 4. I understand from the documentation that the last 3 in the slice function should return this number of words, and count ($ words) - 3 is unclear. - Beginner
    • @Sven, this is starting from which item to return. That is, we start from the third from the end and return three elements. - user3416803
    • and why we ask it from the third from the end, and not from any of all? - Beginner
    • Because the words in the array are arranged in ascending order and we take the three most recent ones (the largest ones). - user3416803
     $str = 'one four three eleven'; // Делим по пробельным символам. // ВНИМАНИЕ: Знаки орфографии и прочие "не" слова останутся $arr = preg_split('/\s+/', $str); // Сортируем по длине строк (самые большие сначала) usort($arr, function($a, $b){ return mb_strlen($a) < mb_strlen($b); }); // Брать первые 2 элемента, которые, после сортировки, самые длинные var_dump(array_slice($arr, 0, 2)); 

    https://repl.it/E8iD/0

      Based on your code

        $a = $_POST ['a']; include '2.html'; function getTop3($a) { $a = explode(' ', $a); $arr = array(); for ($i = 0; $i < count($a); $i++) { if(count($arr) < 3){ array_push($arr, $a[$i]); }else{ $rw = ""; for($t = 0; $t < count($arr); t++){ if(strlen($a[$i]) > strlen($arr[$t])){ if(strlen($arr[$t]) < strlen($rw)){ $rw = $t; }; }; }; array_replace($arr, array($t => $a[$i])); }; }; }; return (array_slice($arr, 0, 3)); } print_r(getTop3($a));