PHP shortest/longest string length in array
Although in this case it is not advisable because you'll be traversing the array twice, you can also use array_reduce to compare each element against the rest. Like this:
<?php
$data = array('163','630','43','42','999','31');
//Will return the longest element that is nearest to the end of the array (999)
//That's why we use strlen() on the result.
$max_l = strlen(array_reduce($data,'maxlen'));
//Will return the shortest element that is nearest to the end of the array (31)
$min_l = strlen(array_reduce($data,'minlen'));
echo "The longest word is $max_l characters, while the shortest is $min_l\n";
function maxlen($k,$v) {
if (strlen($k) > strlen($v)) return $k;
return $v;
}
function minlen($k,$v) {
if ($k == '') return PHP_INT_MAX;
if (strlen($k) < strlen($v)) return $k;
return $v;
}
?>
If you are using PHP 5.3.0+ you can take advantage of closures:
<?php
$max_l = strlen(array_reduce($data,
function ($k,$v) { return (strlen($k) > strlen($v)) ? $k : $v; }
));
$min_l = strlen(array_reduce($data,
function ($k,$v) {
if (!$k) return PHP_INT_MAX;
return (strlen($k) < strlen($v)) ? $k : $v;
}
));
echo "The longest word is $max_l characters, while the shortest is $min_l\n";
?>
Here's an improved version of brian_d's code:
$min = PHP_INT_MAX;
$max = -1;
foreach ($data as $a) {
$length = strlen($a);
$max = max($max, $length);
$min = min($min, $length);
}
$min = 100;
$max = -1;
foreach($data as $a){
$length = strlen($a);
if($length > $max){ $max = $length; }
else if($length < $min){ $min = $length; }
}
Seems like you should use an array_map()
// Convert array to an array of string lengths
$lengths = array_map('strlen', $data);
// Show min and max string length
echo "The shortest is " . min($lengths) .
". The longest is " . max($lengths);
Note that the $lengths
array is unsorted, so you can easily retrieve the corresponding number for each string length.