Ali
Ali

Reputation: 267077

How to get the length of longest string in an array

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

Answers (6)

Ted
Ted

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

Iman Ghafoori
Iman Ghafoori

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

Marco
Marco

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

Heinzi
Heinzi

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

Ben
Ben

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

user187291
user187291

Reputation: 53940

try

$maxlen = max(array_map('strlen', $ary));

Upvotes: 124

Related Questions