foreach PHP loop structures () iterate

foreach () function

(PHP 4, PHP 5, PHP 7)

foreach syntax structure provides through the array simple way. foreach only be applied to arrays and objects, variables attempt if applied to other types of variable data, uninitialized or issues an error message.

There are two syntax:

foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement

The first format: traversing a given array_expression array. In each cycle, the current value of the element is assigned to $ value
and the internal array pointer is advanced by one (so the next cycle will be the next cell).

The second form: doing the same thing, except that the name of the current key unit will be assigned to the variable in each cycle in $ key.

Also be able to customize traverse the object.

Note:

When foreach first starts executing, the internal array pointer to the first element automatically. This means no need to call reset before a foreach loop ().

Since foreach relies on the internal array pointer, whose value is modified in the circulation may lead to unexpected behavior.

1. The code examples (first format)

<?php
$students = array(
'2010'=>'令狐冲',
'2011'=>'林平之',
'2012'=>'曲洋',
'2013'=>'任盈盈',
'2014'=>'向问天',
'2015'=>'任我行',
'2016'=>'冲虚',
'2017'=>'方正',
'2018'=>'岳不群',
'2019'=>'宁中则',
);//10个学生的学号和姓名,用数组存储

//使用循环结构遍历数组,获取学号和姓名  
foreach($students as  $v)
{ 
    echo $v;//输出(打印)姓名
	echo "<br />";
}
?>

operation result:

Here Insert Picture Description
2. The code examples (second format)

<?php
$students = array(
'2010'=>'令狐冲',
'2011'=>'林平之',
'2012'=>'曲洋',
'2013'=>'任盈盈',
'2014'=>'向问天',
'2015'=>'任我行',
'2016'=>'冲虚',
'2017'=>'方正',
'2018'=>'岳不群',
'2019'=>'宁中则',
);//10个学生的学号和姓名,用数组存储

//使用循环结构遍历数组,获取学号和姓名  
foreach($students as  $key=>$value)
{ 
    echo "Key: $key; Value: $value<br />\n";
}
?>

operation result:
Here Insert Picture Description

  • Can easily by adding before $ value & to modify the elements of the array. This will assign reference instead of copying a value.
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // 最后取消掉引用
?>
  • $ Value only if the reference can be referenced in the iterated array can be used (ie is variable). You can not run the following code:
<?php
foreach (array(1, 2, 3, 4) as &$value) {
    $value = $value * 2;
}

?>
  • Warning:
    the end of array elements $ reference value will remain after the foreach loop. Recommended unset () to be destroyed.
Published 17 original articles · won praise 1 · views 884

Guess you like

Origin blog.csdn.net/weixin_43914604/article/details/98314012