In this example I will show you how to find max and min value in a PHP array you will see explanations in the commets of the code.
PHP Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | <?php $arr=[10, 25, 5, 75, 80, 450, 85, 90, 120, 10]; //Declare two variables max and min to store maximum and minimum. //Assume first array element as maximum and minimum both, say $max = arr[0] and $min = arr[0] $min = $arr[0]; $max = $arr[0]; // Iterate through array to find maximum and minimum element in array. //Inside loop for each array element check for maximum and minimum. for ($i = 0; $i < count($arr); $i++) { //Assign current array element to max, if (arr[i] > max) if($arr[$i] > $max) { $max = $arr[$i]; } //Assign current array element to min if if (arr[i] < min) if ($arr[$i] < $min) { $min = $arr[$i]; } } //Print Array Elements echo "Print Array Elements:<br>"; foreach($arr as $item) { echo "$item<br>"; } echo "<br><br>"; //Print max and min number echo "Maximum element:$max<br>"; echo"Minimum element:$min<br>"; |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | Print Array Elements: 10 25 5 75 80 450 85 90 120 10 Maximum element:450 Minimum element:5 |