PHP foreach 语句

foreach 语句


foreach()有两种用法:

1: foreach(array_name as $value)
    {       
    statement;    
    }

这里的array_name是你要遍历的数组名,每次循环中,array_name数组的当前元素的值被赋给$value,并且数组内部的下标向下移一步,也就是下次循环回得到下一个元素。

2:foreach(array_name as $key => $value)
    {
        statement;
     }

 这里跟第一种方法的区别就是多了个$key,也就是除了把当前元素的值赋给$value外,当前元素的键值也会在每次循环中被赋给变量$key。键值可以是下标值,也可以是字符串。比如book[0]=1中的“0”,book[id]="001"中的“id”.


示范用法的更多例子:

<?php
/*-------------------------------------------------------------------------*/
/* foreach example 1: value only */
echo "foreach example 1: value only ".'<br />';

$a = array(1, 2, 3, 17);

foreach ($a as $v) {
   echo "Current value of "$a: $v".'<br />';
}

/*-------------------------------------------------------------------------*/
/* foreach example 2: value (with key printed for illustration) */
echo '<br />'.'<br />'."foreach example 2: value (with key printed for illustration) ".'<br />';

$a = array(1, 2, 3, 17);

$i = 0; /* for illustrative purposes only */

foreach ($a as $v) {
    echo ""$a[$i] => $v".'<br />';
    $i++;
}

/*-------------------------------------------------------------------------*/
/* foreach example 3: key and value */
echo '<br />'.'<br />'."foreach example 3: key and value ".'<br />';

$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);

foreach ($a as $k => $v) {
    echo ""$a[$k] => $v".'<br />';
}

/*-------------------------------------------------------------------------*/
/* foreach example 4: multi-dimensional arrays */
echo '<br />'.'<br />'."foreach example 4: multi-dimensional arrays ".'<br />';

$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2"n";
    }
}

/*-------------------------------------------------------------------------*/
/* foreach example 5: dynamic arrays */
echo '<br />'.'<br />'."foreach example 5: dynamic arrays ".'<br />';

foreach (array(1, 2, 3, 4, 5) as $v) {
    echo "$v"n";
}
?>

结果如下:

foreach example 1: value only 
Current value of $a: 1
Current value of $a: 2
Current value of $a: 3
Current value of $a: 17

foreach example 2: value (with key printed for illustration) 
$a[0] => 1
$a[1] => 2
$a[2] => 3
$a[3] => 17


foreach example 3: key and value 
$a[one] => 1
$a[two] => 2
$a[three] => 3
$a[seventeen] => 17


foreach example 4: multi-dimensional arrays 
a b y z 

foreach example 5: dynamic arrays 
1 2 3 4 5





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值