Difference in the usage of foreach loop in PHP and Java, javaforeach
1. Introduction to foreach statements:
① PHP:
The foreach syntax structure provides a simple way to traverse arrays. Foreach can only be applied to arrays and objects. If you try to apply it to variables of other data types or uninitialized variables, an error message will be sent.
② Java:
The foreach statement is one of the new features of Java 5. In terms of traversing arrays and collections, foreach provides great convenience for developers.
The foreach statement is a special simplified version of the for statement, but the foreach statement cannot completely replace the for statement. However, any foreach statement can be changed to the for statement version.
Foreach is not a keyword. It is used to calling this special for statement format "foreach. Meaning foreach, that is, "for each. This is actually what it means.
2. Syntax format
① Foreach statement format in PHP:
Foreach (array or object name as $ value ){
Statement
}
Or
Foreach (array or object name as $ key => $ value ){
Statement
}
② Foreach statement format in Java:
For (element type t element variable x: traversing object obj ){
References the java Statement of x;
}
3. code example:
① Foreach loop in PHP
<? Php $ arr = array ("1" => "Zhang San", "2" => "Li Si", "3" => "Wang Wu "); foreach ($ arr as $ key => $ value) {echo $ key. "=> ". $ value. "\ n" ;}?> Results: 1 => Zhang San 2 => Li Si 3 => Wang Wu
② Foreach loop in Java
Int arr [] = {2, 3, 1}; for (int x: arr) {System. out. println (x); // outputs the values of array elements one by one} output result: 231