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

报告相同问题?

悬赏问题

  • ¥15 脱敏项目合作,ner需求合作
  • ¥15 脱敏项目合作,ner需求合作
  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密