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.