Introduction to the difference between PHP foreach and for statement usage

Source: Internet
Author: User

Foreach

$tar = Array (

1 => ' East ',

2 => ' West ',

3 => ' Nam ',

4 => ' North ',

5 => ' SE ',

6 => ' Southwest ',

7 => ' ne ',

8 => ' Northwest ',

9 => ' North and South ',

Ten => ' Things ',

);

Code to copy the code as follows

$TM = ' West ';

foreach ($tar as $v => $vv)

{

if ($VV = = $TM)

{

echo $vv. '-$v. '

';

Break

}

Echo $VV;

}

West-2

For

Code to copy the code as follows

Echo '

';

for ($i =1; $i <=count ($tar); $i + +)

{

if ($tar [$i] = = $TM)

{

echo $tar [$i]. ' -'. $i. '

';

Break

}

}

West-2

Summary: foreach and for results are exactly the same, but in the efficiency foreach to win with for, home for need to know the length of the array and then use $i++ to operate, page foreach does not need to know the length of the array can automatically detect and enter the key, and value.

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.