• 6
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

How to get the length of longest string in an array

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?

try

$maxlen = max(array_map('strlen', $ary));
  • 108
Reply Report
    • @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.

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

  • 4
Reply Report

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;
    }
  }
}
  • 1
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions