foreach Loop comparison of several programming languages
The Foreach Loop, as the "enhanced version" of the "for" loop, has been widely used in several programming languages (Java, C #, PHP) because it can traverse array elements in a simpler way. In different languages, however, the specific form of the Foreach loop varies. Below, let's compare the specific structure and application examples of the Foreach loop in Java, C #, and PHP three languages:
1. The Foreach loop is provided after the java:jdk1.5
Syntax format:
for (type variablename:array|collection)
{
VariableName automatically iterates through 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 introduces the foreach structure
Syntax Format 1:
foreach (array_expression as $value)
Statement
Iterates over the given array of array_expression. In each loop, the value of the current cell is assigned to the $value and the pointer inside the array moves forward one step (so the next cell in the next loop will be taken)
Syntax Format 2:
foreach (array_expression as $key = $value)
Statement
In addition to the function of format 1, the key name of the current cell is assigned to the variable $key in each loop.
Starting with PHP 5, it is easy to modify the cells of an array by adding & to it before $value. This method assigns a value to a reference instead of 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 similar to the basic in Java, except that the foreach in C # is "in" (a colon in Java)
Syntax format:
foreach (type variableName in array)
{
VariableName automatically iterates through each element;
}
Example
C # code
Int[] num={1,2,3}; foreach (int i in arr) { System.Console.WriteLine (i); }