2.5.2. Using foreach Loops with Arrays
As we discussed earlier, the easiest way to iterate through—or traverse—an array is using the foreach statement.The foreach statement was specifically introduced in PHP4 to make working with arrays easier.
The foreach statement has two forms:
foreach(array_expression as $value) statement foreach(array_expression as $key => $value) statement
Both iterate through an array expression, executing the body of the loop for each element in the array. The first form assigns the value from the element to a variable identified with the as keyword; the second form assigns both the key and the value to a pair of variables.
The following example shows the first form in which the array expression is the variable $lengths, and each value is assigned to the variable $cm:
// Construct an array of integers $lengths = array(0, 107, 202, 400, 475); // Convert an array of centimeter lengths to inches foreach($lengths as $cm) { $inch = $cm / 2.54; echo "$cm centimeters = $inch inches\n"; }
The example iterates through the array in the same order it was created:
0 centimeters = 0 inches 107 centimeters = 42.125984251969 inches 202 centimeters = 79.527559055118 inches 400 centimeters = 157.48031496063 inches 475 centimeters = 193.87755102041 inches
The first form of the foreach statement can also iterate through the values of an associative array, however the second form assigns both the key and the value to variables identified as $key => $value. The next example shows how the key is assigned to $animal, and the value is assigned to $sound to generate verses of "Old MacDonald":
// Old MacDonald $sounds = array("cow"=>"moo", "dog"=>"woof", "pig"=>"oink", "duck"=>"quack"); foreach ($sounds as $animal => $sound) { echo "<p>Old MacDonald had a farm EIEIO"; echo "<br>And on that farm he had a $animal EIEIO"; echo "<br>With a $sound-$sound here"; echo "<br>And a $sound-$sound there"; echo "<br>Here a $sound, there a $sound"; echo "<br>Everywhere a $sound-$sound"; }
This prints a verse for each $animal/$sound pair in the $sounds array:
Old MacDonald had a farm EIEIO And on that farm he had a cow EIEIO With a moo-moo here And a moo-moo there Here a moo, there a moo Everywhere a moo-moo Old MacDonald had a farm EIEIO And on that farm he had a dog EIEIO With a woof-woof here And a woof-woof there Here a woof, there a woof Everywhere a woof-woof
When the second form of the foreach statement is used with a nonassociative array, the index is assigned to the key variable and the value to the value variable. The following example uses the index to number each line of output:
// Construct an array of integers $lengths = array(0, 107, 202, 400, 475); // Convert an array of centimeter lengths to inches foreach($lengths as $index => $cm) { $inch = $cm / 2.54; $item = $index + 1; echo $index + 1 . ". $cm centimeters = $inch inches\n"; }
The foreach statement is used throughout Chapter 4 to Chapter 13.
Write a Java program to get the difference between the largest and smallest values in an array of integers. The length of the
array must be 1 and above. Pictorial Presentation: Sample Solution: Java Code:Java Array Exercises: Get the difference between the largest and smallest values in an array of integers
Last update on August 19 2022 21:50:33 (UTC/GMT +8 hours)Java Array: Exercise-28 with Solution
Sample Output:
Original Array: [5, 7, 2, 4, 9] Difference between the largest and smallest values of the said array: 7Flowchart:
Visualize Java code execution (Python Tutor):
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Java program to find the number of even and odd integers in a given array of integers.
Next: Write a Java program to compute the
average value of an array of integers except the largest and smallest values.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
Avoiding Memory leaks by simple tricks:
Memory leaks often cause performance degradation of software. Since, Java manages memory automatically, the developers do not have much control. But there are still some standard practices which can be used to protect from memory leakages.
- Always release database connections when querying is complete.
- Try to use Finally block as often possible.
- Release instances stored in Static Tables.
Ref: //bit.ly/3nXDDhw
- Exercises: Weekly Top 16 Most Popular Topics
- SQL Exercises, Practice, Solution - JOINS
- SQL Exercises, Practice, Solution - SUBQUERIES
- JavaScript basic - Exercises, Practice, Solution
- Java Array: Exercises, Practice, Solution
- C Programming Exercises, Practice, Solution : Conditional Statement
- HR Database - SORT FILTER: Exercises, Practice, Solution
- C Programming Exercises, Practice, Solution : String
- Python Data Types: Dictionary - Exercises, Practice, Solution
- Python Programming Puzzles - Exercises, Practice, Solution
- C++ Array: Exercises, Practice, Solution
- JavaScript conditional statements and loops - Exercises, Practice, Solution
- C# Sharp Basic Algorithm: Exercises, Practice, Solution
- Python Lambda - Exercises, Practice, Solution
- Python Pandas DataFrame: Exercises, Practice, Solution
- Conversion Tools
- JavaScript: HTML Form Validation