Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the length of longest string in an array

Tags:

arrays

php

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?

like image 245
Ali Avatar asked Nov 19 '09 10:11

Ali


People also ask

How do you find the longest string in an array C++?

I wrote this code: char a[100][100] = {"solol","a","1234567","123","1234"}; int max = -1; for(int i=0;i<5;i++) if(max<strlen(a[i])) max=strlen(a[i]); cout<<max; The output it gives is -1. But when I initialize the value of max by 0 instead of 1, the code works fine.

How do you find the longest word in a string?

function findLongestWord(str) { var longestWord = str. split(' '). reduce(function(longest, currentWord) { return currentWord. length > longest.


2 Answers

try

$maxlen = max(array_map('strlen', $ary)); 
like image 161
user187291 Avatar answered Sep 22 '22 00:09

user187291


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

like image 24
Heinzi Avatar answered Sep 22 '22 00:09

Heinzi