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?
try
$maxlen = max(array_map('strlen', $ary));
"strlen"
is beautiful, you should look at JavaScript that passes strlen
directly or Java that passes ::strlen
instead. Passing strings as callables is the source of a lot of language design problems in PHP. 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;
}
}
}
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. ;-)
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)];
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;
});
you can use array_reduce to get the max length of string in array
$strings = array("Hello", "world", "this", "is", "a", "test");
$longest = array_reduce($strings, function($c, $v) {
return max($c, strlen($v));
}, 0);
echo "The longest string has a length of $longest characters.";
In this example, $strings is an array of strings, and array_map() applies the strlen() function to each element of the array, resulting in an array of string lengths. Then max() function is used to find the maximum value in this array. The result is stored in the $longest variable and printed out.