Home » Php » php – How to get the length of longest string in an array

php – How to get the length of longest string in an array

Posted by: admin April 23, 2020 Leave a comment

Questions:

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?

How to&Answers:

try

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

Answer:

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. 😉

Answer:

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