41

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?

0

6 Answers 6

125

try

$maxlen = max(array_map('strlen', $ary)); 
Sign up to request clarification or add additional context in comments.

1 Comment

@Tobia If you are saying that "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.
4

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

2 Comments

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

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

Comments

1

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

3 Comments

but the question clearly said "without looping through the array and checking each element?"
basic mechanics of doing such a task is still "looping", using array_map() for example just make it transparent to the user.
if you want to get a specified item from a set you will always have to loopthrough the set. In one way, or another. ;)
0

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

Comments

0

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.