$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