4

Here is part of the code.

$DatabaseArray=Array("Cooking","look","I cant","Walking the dog to the park","washing","talk","one");
  
$largest = max($DatabaseArray);
  
echo $largest. "<br />";

I would like to read the longest string from an array in PHP 5.3.0. I've tried the max function but doesnt seem to work as expected.

miken32
  • 42,008
  • 16
  • 111
  • 154
Staypa
  • 253
  • 1
  • 5
  • 13

3 Answers3

9
$longestEntry = array_reduce($databaseArray, function ($a, $b) { return strlen($a) > strlen($b) ? $a : $b; });

(uses PHP 5.3 syntax)

You can't just use max, since that assumes all entries are numbers. Since they're strings though, "the maximum string" could mean anything, so you have to do manual comparison using strlen. The above array_reduce method with custom reduce function does such comparison and reduces the array to the longest member.

If you have a lot of entries (and I mean a lot, hundreds or thousands and up), it may not be very efficient, since it basically applies strlen twice to the whole array. If that's a problem, this is more efficient by applying strlen only once per string:

$longestEntry = current(array_reduce($databaseArray, function ($a, $b) {
    $b = array($b, strlen($b));
    return $a[1] > $b[1] ? $a : $b;
}, array(null, 0)));

Since you're calling it a DatabaseArray though: If this is coming from the database, you should make it do the work. It's probably going to be even more efficient. E.g.:

SELECT * FROM `table` ORDER BY CHAR_LENGTH(`string_col`) DESC LIMIT 1
deceze
  • 510,633
  • 85
  • 743
  • 889
7
$lengths = array_map('strlen', $DatabaseArray);
$maxLength = max($lengths);
$index = array_search($maxLength, $lengths);
echo $DatabaseArray[$index];
KingCrunch
  • 128,817
  • 21
  • 151
  • 173
  • This code is returning the index rather than the longest the longest element in the array. – Staypa Jul 12 '11 at 07:43
  • 2
    You are talking about line 3. The last line gives you the element itself. – KingCrunch Jul 12 '11 at 07:49
  • Thanks man I hadn't noted because My database is very populated and there's no page break in your code. Thanks full time it's working!!!! – Staypa Jul 12 '11 at 08:05
0

Like @deceze's answer, my suggestion is a single pass over the input array. @KingCrunch's has a greater cost in terms of time complexity because it is using functions to traverse the data more N times.

Below has the same fundamental logic as @deceze's PHP snippet, but uses intuitive, individual variables instead of indexed elements for temporary storage.

Code: (Demo)

$maxLength = -1;
$longestValue = null;
foreach ($array as $value) {
    $length = strlen($value);
    if ($length > $maxLength) {
        $maxLength = $length;
        $longestValue = $value;
    }
}
var_export($longestValue);

Output:

'Walking the dog to the park'
mickmackusa
  • 43,625
  • 12
  • 83
  • 136