Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Get Longest String in Array without loop [duplicate]

Tags:

arrays

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

like image 449
100r0bh Avatar asked Apr 25 '26 01:04

100r0bh


1 Answers

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

like image 96
The fourth bird Avatar answered Apr 26 '26 15:04

The fourth bird