I would like to return the longest string in an array in php 4.0 my sample code looks like this.
$MyArray=Array("Jane","Magdalene","Bull fighting champion","cruising","Tommy Lee Jones","View","axe");
$largest = max($MyArray);
echo $largest.
max()
is to give the maximum from a list of integers. Unfortunately, your problem is more complicated.
<?php
$MyArray=Array("Jane","Magdalene","Bull fighting champion","cruising","Tommy Lee Jones","View","axe");
$maxlen = 0;
$idx = -1;
for ($i=count($MyArray); $i; $i--) {
$len = strlen($MyArray[$i-1]);
if ($len > $maxlen) {
$maxlen = $len;
$idx = $i-1;
};
}
if ($idx >0) {
echo $MyArray[$idx];
}
$longest = $MyArray[0];
foreach( $MyArray as $str ) {
if ( strlen( $str ) > strlen( $longest ) ) {
$longest = $str;
}
}
You can try this:
$lengths = array();
for($i=0; $i<count($MyArray); $i++) {
$lengths[$myArray[$i]] = strlen($MyArray[$i]);
}
arsort($lengths);
echo key($lengths);
And the compact version without manual loops:
$array = array_combine($array, array_map("strlen", $array));
arsort($array);
print key($array);