Reputation: 267077
Say I have this array:
$array[] = 'foo';
$array[] = 'apple';
$array[] = '1234567890;
I want to get the length of the longest string in this array. In this case the longest string is 1234567890
and its length is 10.
Is this possible without looping through the array and checking each element?
Upvotes: 41
Views: 21824
Reputation: 4166
This's how to get the longest string "itself" from an array
$array = ['aa', 'b', 'c'];
$longest_str = array_reduce($array, fn ($carry, $item) => strlen($item) > strlen($carry) ? $item : $carry, "");
echo $longest_str; // aa
Upvotes: 0
Reputation: 31
This way you can find the shortest (or longest) element, but not its index.
$shortest = array_reduce($array, function ($a, $b) {
if ($a === null) {
return $b;
}
return strlen($a) < strlen($b) ? $a : $b;
});
Upvotes: 0
Reputation: 3641
A small addition to the ticket. I came here with a similar problem: Often you have to output just the longest string in an array.
For this, you can also use the top solution and extend it a little:
$lengths = array_map('strlen', $ary);
$longestString = $ary[array_search(max($lengths), $lengths)];
Upvotes: 2
Reputation: 172270
Sure:
function getmax($array, $cur, $curmax) {
return $cur >= count($array) ? $curmax :
getmax($array, $cur + 1, strlen($array[$cur]) > strlen($array[$curmax])
? $cur : $curmax);
}
$index_of_longest = getmax($my_array, 0, 0);
No loop there. ;-)
Upvotes: 4
Reputation: 11188
Loop through the arrays and use strlen
to verify if the current length is longer than the previous.. and save the index of the longest string in a variable and use it later where you need that index.
Something like this..
$longest = 0;
for($i = 0; $i < count($array); $i++)
{
if($i > 0)
{
if(strlen($array[$i]) > strlen($array[$longest]))
{
$longest = $i;
}
}
}
Upvotes: 1