Usage differences between the foreach loops in PHP and Java

Source: Internet
Author: User

1. The foreach statement describes:

①php:

The foreach syntax structure provides an easy way to iterate through an array. foreach can only be applied to arrays and objects, if you try to apply a variable to another data type, or an uninitialized variable will emit an error message.

②java:

The foreach statement is one of the new features of Java5, and foreach provides developers with great convenience in traversing arrays and collections.
The foreach statement is a special simplified version of the for statement, but the foreach statement does not completely replace the For statement, however, any foreach statement can be rewritten as a version of the for statement.
foreach is not a keyword, and it is customary to call this special for-statement format a "foreach" statement. To understand the meaning of foreach as "for each" from the literal meaning of English. That's actually what this means.

2. Syntax format

Statement format for foreach in ①php:

foreach (array or object name as $value) {

Statement

}
Or

foreach (array or object name as $key = = $value) {

Statement

}

Statement format for foreach in ②java:
for (element type T element variable x: Traverse object obj) {
A Java statement that references X;
}

3. code example:

foreach loops in the ①php

<?php $arr = Array ("1" = "Zhang San", "2" = "John Doe", "3" = "Harry"), and foreach ($arr as $key = = $value) {  echo $key. = ". $value." \ n ";}?" > results are as follows:1=> Zhang San 2=> John Doe 3=> Harry

foreach loops in the ②java

int arr[] = {2, 3, 1}; for (int x:arr) {System.out.println (x);//Output The value of the array element individually} output result: 231

  

  

Usage differences between the foreach loops in PHP and Java

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.