-4
$array =array("AB","ABC","ABCD","ABCDE","BD");

Requirement: find the longest element in the array

Output:ABCDE
YetAnotherBot
  • 1,937
  • 2
  • 25
  • 32

4 Answers4

1
$array =array("AB","ABC","ABCD","ABCDE","BD");

$longstring = $array[0];
foreach( $array as $string ) {
if ( strlen( $string ) > strlen( $longstring ) ) {
$longstring = $string;
    }
}

echo $longstring;
Dirk J. Faber
  • 4,360
  • 5
  • 20
  • 58
  • This outputs the actual string. Shivruda's answer will give you the length of the longest string. – Dirk J. Faber Jul 15 '18 at 11:13
  • You are welcome. If you feel your question has been answered, make sure to mark the most helpful answer as the right answer so the question is marked as 'answered'. – Dirk J. Faber Jul 15 '18 at 12:03
0

First we are iterate the array with help of foreach loop. in foreach loop we check $result is less than array value. if array value is greater then $result array then we override previous value of $result with new value. if we found greatest length than previous array element then we are storing new length & key of new element in variable.

   $array =array("AB","ABC","ABCD","ABCDE","BD"); 
    $result = $resultkey = 0;
    foreach($array as $key=>$value) {

        if($result < strlen($value) ) {
            $result = strlen($value);
            $resultkey = $key;
        }
    }
    echo 'longest value:' $result;
    echo 'result :'   $array[$resultkey]

Output:

longest value:  5
result :ABCDE
Shivrudra
  • 674
  • 4
  • 5
0

Try this, though it's a bit confusing.

<?php //php 7.0.8

$array = array("AB","ABC","ABCD","ABCDE","BD");

$longertext = array_search(max($array), $array)-1; //4-1 =3

// minus 1 because it's counting the actual position not starts with 0 it returns 4

echo $longertext;  //equals 3
echo "\n";
echo $array[$longertext];  //equals  ABCDE

?>

The actual test: http://rextester.com/OTI23127

Pang
  • 9,564
  • 146
  • 81
  • 122
bdalina
  • 503
  • 10
  • 16
0

You could sort the array by string length using strlen and usort and get the first item:

$array =array("AB","ABC","ABCD","ABCDE","BD");
usort($array, function($x, $y) { return strlen($y)-strlen($x); });
echo $array[0];

Result:

ABCDE

Demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70