Introduction to the difference between php foreach and for statement usage_PHP tutorial

WBOY
Release: 2016-07-21 14:51:39
Original
1170 people have browsed it

 //foreach

 $tar = array (

 1 => '东',

 2 => '西',

 3 => 'South',

 4 => 'North',

 5 => 'Southeast',

 6 => 'Southwest',

 7 => 'Northeast',

 8 => 'Northwest',

 9 => 'North and South',

 10 => 'something',

 );

The code is as follows. Copy the code

$TM = '西';

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

 {

 if( $vv == $TM )

 {

echo $vv.'-'.$v.'

 ;

break;

 }

//echo $vv;

 }

 //West-2

 //for

The code is as follows. Copy the code

echo '

 ;

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

 {

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

 {

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

 ;

break;

 }

 }

 //West-2

Summary: The results of foreach and for are exactly the same, but foreach is better than for in terms of efficiency. For on the home page, you need to know the array length and then use $i++ to operate. Foreach on the page does not need to know the array length and can automatically detect and enter the key. , and value.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/371795.htmlTechArticle//foreach $tar = array ( 1 = 'East', 2 = 'West', 3 = 'South ', 4 = 'North', 5 = 'Southeast', 6 = 'Southwest', 7 = 'Northeast', 8 = 'Northwest', 9 = 'North and South', 10 = 'East and West', ); The code is as follows Copy the code ...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!