tags:

views:

191

answers:

3

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?

+9  A: 

try

$maxlen = max(array_map('strlen', $ary));
stereofrog
Did anyone tell you you're a genius???
Click Upvote
nope you're the first ;))))
stereofrog
strange!! that code was genius
Click Upvote
+1  A: 

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;
    }
  }
}
Ben Fransen
but the question clearly said "without looping through the array and checking each element?"
pavium
basic mechanics of doing such a task is still "looping", using array_map() for example just make it transparent to the user.
ghostdog74
if you want to get a specified item from a set you will always have to loopthrough the set. In one way, or another. ;)
Ben Fransen
+1  A: 

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. ;-)

Heinzi
Disclaimer: I did understand that "no looping" in the question also implied "no recursion", but I could not resist...
Heinzi
Great answer :PI would vote you up, had I not reached my vote limit for the day...
Franz