$array =array("AB","ABC","ABCD","ABCDE","BD");
Requirement: find the longest element in the array
Output:ABCDE
$array =array("AB","ABC","ABCD","ABCDE","BD");
Requirement: find the longest element in the array
Output:ABCDE
$array =array("AB","ABC","ABCD","ABCDE","BD");
$longstring = $array[0];
foreach( $array as $string ) {
if ( strlen( $string ) > strlen( $longstring ) ) {
$longstring = $string;
}
}
echo $longstring;
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
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
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