Difference in the usage of foreach loop in PHP and Java, javaforeach

Source: Internet
Author: User

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

  

  

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.