How do I get the highest value when using loops?
I want to get the highest value of my array. This are the two ways when I'm working with php functions.
$a = array(1,125,1068);
1. $value = max($a);
print_r ($value);
2. asort($a);
$value = end($a);
print_r ($value);
I just couldn't fig开发者_运维技巧ure out how to get the highest value when using loops.
You do it like this:
$highest = 0;
//if you have negative values: $highest = min($a);
foreach($a as $item){
if ($item > $highest){
$highest = $item;
}
}
Without using the max() function, you can do something like
<?php
$a = array(1,125,1068)
$max = $a[0];
for ($i = 1; $i <count($a); $i++) {
if ($a[$i] > $max) {
$max = $a[$i];
}
}
echo $max; ?>
max()
http://php.net/manual/en/function.max.php
$dd = array(50, -25, -5, 80, -40, -152, -45, 28, -455, 100, 98, -455);
$curr = '';
$max = $dd[0];
for($i = 0; $i < count($dd); $i++) {
$curr = $dd[$i];
if($curr >= $max) {
$max = $curr;
}
}
精彩评论