How to find the longest string in an array of strings in PHP

1 Answer

0 votes
$strings = ["c++", "php", "python", "c#", "java", "swift"];

$longest_string = array_reduce($strings, function($a, $b) {
    if ($a == null) $a = $b;
    if ($b == null) $b = $a;
    
    return (strlen($a) > strlen($b)) ? $a : $b;
});

echo $longest_string;


/*
run:

python

*/

 



answered Oct 2, 2024 by avibootz
...