Code that stores 10 random numbers in an array
$numbers = array();
for ($i = 0; $i < 10; $i++) {
$numbers[] = mt_rand(1, 100);
}
Code that displays the elements of an array
$numbers_string = '';
for ($i = 0; $i < count($numbers); $i++) {
$numbers_string .= $numbers[$i] . ' ';
}
echo($numbers_string);
74 79 78 75 4 84 77 85 61 31
Code that computes the sum and average of an array of prices
$prices = array(141.95, 212.95, 411, 10.95);
$sum = 0;
for ($i = 0; $i < count($prices); $i++) {
$sum += $prices[$i];
}
$average = $sum / count($prices);
How to skip gaps in an array
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
unset($numbers[2], $numbers[6]);
end($numbers);
$last = key($numbers);
$numbers_string = '';
for($i = 0; $i <= $last; $i++) {
if (isset($numbers[$i])) {
$numbers_string .= $numbers[$i] . ' ';
}
}
echo($numbers_string;) // Displays: 1 2 4 5 6 8 9 10
- For loops are commonly used to process the data in arrays. In this case, the counter for the loop is used as the index for each element in the array.
Back