How to get the length of longest string in an array

Viewed 18779

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?

5 Answers

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;
});
Related