Home >Backend Development >PHP Tutorial >Comparison of foreach loops in several programming languages
Comparison of foreach loops in several programming languages
As an "enhanced version" of the "for" loop, the foreach loop has been used in several programming languages (Java, C#, PHP) because it can traverse array elements in a simpler way. has been widely used. But in different languages, the specific form of foreach loop is different. Next, let’s compare the specific structure and application examples of foreach loop in Java, C# and PHP:
1. Java: After JDK1.5, a foreach loop is provided
Syntax format:
for (type variableName : array|collection)
{
variableName automatically iteratively accesses each element;
}
instance
Java code
public class Test1 { public static void main(String[] args) { String[] names = {"Jerry","Tom","Spike"}; for(String name : names) System.out.println(name); } }
2. PHP: PHP 4 introduced the foreach structure
Syntax format 1:
foreach (array_expression as $value)
PHP In each loop, the value of the current unit is assigned to $value and the pointer inside the array moves forward one step (so the next unit will be obtained in the next loop)
Syntax format 2:
foreach (array_expression as $key = & gt; $ value)
Statement
Except for the function of format 1, the key name of the current unit will also be assigned to the variable $ key in each cycle.
Since PHP 5, it is easy to modify the cells of an array by adding & before $value. This method assigns by reference rather than copying a value.
Php code
<?php $arr = array(1, 2, 3, 4); foreach ($arr as & $value) { $value = $value * 2; } // $arr is now array(2, 4, 6, 8) ?>3. C#: The foreach method in C# is basically similar to that in Java, but please note that the foreach in C# is followed by "in" (colon in Java)
Grammar format:
foreach(type variableName in array)
{ variableName automatically iterates to access each element;
}
Instance
C# code
int[] num={1,2,3}; foreach(int i in arr) { System.Console.WriteLine(i); }