Home > Backend Development > PHP Tutorial > Foreach in PHP traverses more than just arrays

Foreach in PHP traverses more than just arrays

autoload
Release: 2023-04-09 20:00:02
Original
3300 people have browsed it

1.Foreach format

foreach (array_expression as $value)
   statement
foreach (array_expression as $key => $value)
   statement
Copy after login

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,&#39;<br/>&#39;;//1 2 3 4 5 6 7 8 9 10 11
} 
?>
Copy after login

b. Method 2:

<?php
$arr = array(1, 2, 3, 4,7,8,9,10,11);
foreach($arr as $a => $v)
{
    echo &#39;key&#39;,$a,&#39;== value&#39;,$v,&#39;<br/>&#39;;
}
// key0== value1
// key1== value2
// key2== value3
// key3== value4
// key4== value7
// key5== value8
// key6== value9
// key7== value10
// key8== value11
?>
Copy after login

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 = &#39;LiLei&#39;;
    public $height = 178;
    public $weight = 140;
    protected $age = 30;
    private $money = 1000;
}
//实例化
$m = new Man();
//遍历
foreach($m as $k => $v){
    echo $k . &#39; : &#39; . $v . &#39;<br/>&#39;;		//$k为属性名,$v为属性值
}
/* name : LiLei
   height : 178
   weight : 140
 */
Copy after login

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!

Related labels:
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