在PHP中查找一维数组中最长和第二长的字符串

时间:2018-04-23 16:31:32

标签: php

有人可以帮忙吗? 我试图在php中打印出最长的字符串和第二长的字符串

function findLongestStringFromArray($array = array()) {

    if(!empty($array)){
        $length_of_arr = array_map('strlen', $array); 
        $maxLength = max($length_of_arr); // find highest value in the array
        $key = array_search($maxLength, $length_of_arr);
        $key2 = array_search(next($maxLength), $length_of_arr);
        return array(
            'length' => $maxLength,
            'postion' => $key,
            'longest-string'=>$array[$key],
            'secondLongest-string'=>$array[$key2]
        );
    }
}
$arrData = array("car", "paper", "pencil", "football", "databases");
print_r(findLongestStringFromArray($arrData));

然后我收到此错误消息 Warning: next() expects parameter 1 to be array, integer given in C:\xampp\htdocs\php\lab2.php on line 134 Array ( [length] => 13 [postion] => 4 [longest- string] => databases [secondLongest-string] => car)

1 个答案:

答案 0 :(得分:0)

我建议采用不同的方法。按strlen的降序对输入数组进行排序,然后使用array_slice返回前两个元素。

function findLongestStringFromArray($array = array()) {
    usort($array, function($a, $b) {
        return strlen($b) - strlen($a);
    });
    $longest = array_slice($array, 0, 2);
    return array_combine(['longest-string','secondLongest-string'], $longest);
}

要包括长度和位置,您需要使用uasort代替usort来保留密钥。

function findLongestStringFromArray($array = array()) {
    uasort($array, function($a, $b) {
        return strlen($b) - strlen($a);
    });
    return [
        'length' => strlen(reset($array)),
        'position' => key($array),
        'longest-string' => reset($array),
        'secondLongest-string' => next($array)
    ];
}