Home> php教程> php手册> body text

php foreach与for语句用法区别介绍

WBOY
Release: 2016-06-13 11:34:12
Original
1233 people have browsed it

  //foreach

  $tar = array (

  1 => '东',

  2 => '西',

  3 => '南',

  4 => '北',

  5 => '东南',

  6 => '西南',

  7 => '东北',

  8 => '西北',

  9 => '南北',

  10 => '东西',

  );

  代码如下 复制代码

  $TM = '西';

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

  {

  if( $vv == $TM )

  {

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

  ';

  break;

  }

  //echo $vv;

  }

  //西-2

  //for

  代码如下 复制代码

  echo '

  ';

  for( $i=1;$i

  {

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

  {

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

  ';

  break;

  }

  }

  //西-2

  总结:foreach与for结果是完全相同的,但在效率上foreach要胜与for,首页for需要知道数组长度再用$i++来操作,页foreach不需要知道数组长度可自动检测并输入key,和value。

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 Recommendations
    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!