duanche8554 2019-07-13 08:49
浏览 360
已采纳

PHP在没有循环的情况下获取数组中最长的字符

Given an array, I want to get the longest string by length without using the foreach loop.

Below is my array

$array = array(
    'Google',
    'Facebook',
    'Twitter',
    'Slack',
    'Twilio',
);

This question returns the maximum length but I want to get the value of the string. PHP shortest/longest string in array

  • 写回答

4条回答 默认 最新

  • doukui4836 2019-07-13 09:01
    关注

    You could sort the strings by length using for example usort and get the first item using reset.

    $array = array(
        'Google',
        'Facebook',
        'Twitter',
        'Slack',
        'Twilio',
    );
    
    usort($array, function ($a, $b) {
        return strlen($a) < strlen($b);
    });
    
    echo reset($array); // Facebook
    

    If there could be more strings with equal length, you could use a foreach and break out of the loop when the length is not equal to the current length of the item to prevent looping the whole list.

    $item = reset($array);
    $result = [];
    
    if ($item) {
        $len = strlen($item);
        foreach($array as $value) {
            if (strlen($value) === $len) {
                $result[] = $value;
                continue;
            }
            break;
        }
    }
    
    print_r($result);
    

    Result

    Array
    (
        [0] => Facebook
        [1] => Test1112
    )
    

    Php demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?