Chociaż w tym przypadku nie jest wskazane, bo ciebie” ll być przejeżdżające tablicę dwukrotnie, można również użyć array_reduce porównać każdy element przed resztą jak ten:.
<?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;
}
?>
Jeżeli jesteś PHP 5.3.0+ można wykorzystać 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";
?>
Czy chcesz tylko długość struny, czy też chcesz struny? – NullUserException
Sądzę, że oba są przydatne. –
Powinieneś był usunąć zamieszanie długości/wartości, używając ciągów zamiast tych liczb. –