2

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

1
  • What happens when multiple elements tie for maximum length? Commented Jul 13, 2019 at 10:50

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

While appropriate for the posted sample input, this solution does not respect the possibility that the input can possibly contain multiple values which share the maximum length.
@mickmackusa That is correct, I have added a possible solution for multiple strings.
Is that multi-longest solution not already provided by vivek_23? Wait, are you saying you want to iterate the array with usort() which calls strlen() two times per iteration, then call array_filter() to iterate all of the elements again and call strlen() two more times per iteration?!? You wouldn't actually use a solution like that would you? Why would you recommend such a technique to anyone? Researchers are more likely to blindly trust your answers because of your high rep points -- I think you have a duty to provide your best possible solution.
@mickmackusa I missed that vivek_23 had the same solution using array_filter. I have updated it to calculate the strlen once and break out of the foreach when the lengths are not equals any more.
3

I find the restriction of "no foreach loop" to be maddeningly restrictive. After all, you need to iterate the array to perform this process. Any syntax that you choose will need to "loop" under the hood anyhow.

For this reason, I am casting your restriction away so that I can show you a clean and efficient approach that doesn't make excessive function calls AND honors the possibility of multiple "longest" values.

Code: (Demo)

$array = array(
    'Google',
    'Facebook',
    'Twitter',
    'Slack',
    'Twilio',
    'Bookface'
);
$cachedLength = 0;
$longest = [];

foreach ($array as $value) {
    $currentLength = strlen($value);
    if ($currentLength > $cachedLength) {
        $longest = [$value];
        $cachedLength = $currentLength;
    } elseif ($currentLength == $cachedLength) {
        $longest[] = $value;
    }
}
var_export($longest);

Output:

array (
  0 => 'Facebook',
  1 => 'Bookface',
)

To clarify, $longest = [$value]; declares (or overwrites an earlier declared) $longest array. In doing so, you never see any smaller values pushed into the array.

If a subsequent value has the same length as the one stored in $longest, then $longest[] = $value; pushes it into the output array.

This snippet will call strlen() only one time per element. There are not additional function calls to produce the desired output. This is the approach that I would use if this was going into a professional project.

Comments

2

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

Without using foreach loop(or any loop for instance), it is not possible to get the data. The wrappers like array_filter,array_map etc do loop under the hood. Extending from the answer you linked, you could just use array_filter to filter out the strings that have the longest length.

<?php 

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

$lengths = array_map('strlen', $data);

$max_len = max($lengths);

$longest_strings = array_filter($data,function($value) use ($max_len){
    return strlen($value) === $max_len;
});

print_r($longest_strings);

Comments

0

You can use array_walk to get the length of each array element, than use array_search with max to get highest length element

$r = null;
array_walk($array, function($v) use (&$r){
  $r[$v] = strlen($v);
});
echo array_search(max($r), $r);

Live Example : https://3v4l.org/ETf9F

2 Comments

Thanks but I went with the other answer as that was compact.
@100r The other may have 1 less line of code, but it is doing 2 strlen() calls per iteration of all of the elements (n*2). This answer calls strlen() n*1, then runs a second loop (array_search()) with an early break point (which may be another full n iterations).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.