What is the best approach to store and compare values in a foreach loop in PHP?
When storing and comparing values in a foreach loop in PHP, it is important to initialize variables outside of the loop to store the values for comparison. Within the loop, you can update these variables based on your comparison logic. Finally, you can use the updated variables outside of the loop to access the desired values.
<?php
// Initialize variables outside of the loop
$highestValue = 0;
$lowestValue = PHP_INT_MAX;
$values = [10, 5, 20, 15];
foreach ($values as $value) {
// Compare values and update variables
if ($value > $highestValue) {
$highestValue = $value;
}
if ($value < $lowestValue) {
$lowestValue = $value;
}
}
// Access the highest and lowest values outside of the loop
echo "Highest value: $highestValue\n";
echo "Lowest value: $lowestValue\n";
?>