Home >Backend Development >PHP Tutorial >Introduction to the difference between php foreach and for statement usage_PHP tutorial

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-21 14:51:391267browse

 //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 ...
Statement:
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