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

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条)

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退