How to get the length of longest string in an array

后端 未结 3 1955
说谎
说谎 2020-12-05 17:32

Say I have this array:

$array[] = \'foo\';
$array[] = \'apple\';
$array[] = \'1234567890;

I want to get the length of the longest string in

相关标签:
3条回答
  • 2020-12-05 17:40

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

    0 讨论(0)
  • 2020-12-05 17:42

    try

    $maxlen = max(array_map('strlen', $ary));
    
    0 讨论(0)
  • 2020-12-05 17:58

    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;
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题