Home > Article > Backend Development > Foreach in PHP traverses more than just arrays
1.Foreach format
foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement
2.Foreach traversal of the array
a. Method 1 :
<?php $arr = array(1, 2, 3, 4,7,8,9,10,11); foreach($arr as $a) { echo $a,'<br/>';//1 2 3 4 5 6 7 8 9 10 11 } ?>
b. Method 2:
<?php $arr = array(1, 2, 3, 4,7,8,9,10,11); foreach($arr as $a => $v) { echo 'key',$a,'== value',$v,'<br/>'; } // key0== value1 // key1== value2 // key2== value3 // key3== value4 // key4== value7 // key5== value8 // key6== value9 // key7== value10 // key8== value11 ?>
3.foreach traverses the object
Traverses the object
, in fact, it means to take out and access all attributes (public attributes)
in the object in the form of key-value pairs
.
//定义类 class Man{ public $name = 'LiLei'; public $height = 178; public $weight = 140; protected $age = 30; private $money = 1000; } //实例化 $m = new Man(); //遍历 foreach($m as $k => $v){ echo $k . ' : ' . $v . '<br/>'; //$k为属性名,$v为属性值 } /* name : LiLei height : 178 weight : 140 */
Recommended: php video tutorial php tutorial
The above is the detailed content of Foreach in PHP traverses more than just arrays. For more information, please follow other related articles on the PHP Chinese website!