How to get the length of longest string in an array

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


try

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

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

Tags:

Php

Arrays