使用索引变量

索引变量用作添加变量,用于演示任何迭代中 foreach 循环的索引。

下面是一个例子:

<?php 
//声明一个数组
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); 
$index = ;
foreach($arr as $key=>$val) {
    echo "The index is $index";
    $index++;
    echo "\n";
}
?>

必须考虑索引变量最初应该用一个值初始化。
之后,它会在循环迭代时递增。

输出将如下所示:

The index is 0
The index is 1
The index is 2
The index is 3
The index is 4
The index is 5
The index is 6
The index is 7
The index is 8
The index is 9

使用键和索引变量

现在,让我们看看如何同时使用键和索引变量。

下面是一个例子:

<?php 

//声明一个数组
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); 
$index = ;
foreach ($arr as $key=>$value) {    
    echo "The index is $index";
    $index = $key+;
    echo "\n";
}

?>

在上面的示例中,键变量的值在索引变量中保持递增。
因此,在这种情况下,键和索引变量都用于查找 foreach 的索引。

使用key变量

key 变量包含 foreach 循环内每个值的索引。
在 PHP 中,foreach 循环是这样使用的:

foreach($arrayName as $value){
    //code
}

value 变量包含数组中每个元素的值。
下面是一个例子:

<?php 
$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); 
foreach ($array as $key => $value) { 
    echo "The index is = " . $key . ", and value is = ". $value; 
    echo "\n";
}   
?>

其中key 变量存储了 foreach 循环的索引。
变量值展示了数组中每个元素的值。

输出将如下所示:

The index is = 0, and the value is = 1
The index is = 1, and the value is = 2
The index is = 2, and the value is = 3
The index is = 3, and the value is = 4
The index is = 4, and the value is = 5
The index is = 5, and the value is = 6
The index is = 6, and the value is = 7
The index is = 7, and the value is = 8
The index is = 8, and the value is = 9
The index is = 9, and the value is = 10
如何使用 PHP 查找 foreach 索引

在本教程中,我们为我们提供了在 PHP 中查找 foreach 索引的有用方法。

PHP 中的 foreach 循环

在 PHP 中,foreach 循环用于循环遍历数组中每个元素的代码块。
需要注意的是,foreach 循环只对对象和数组进行操作。
一旦我们尝试在具有不同数据类型的变量上使用它,它将发出错误。

日期:2020-06-02 22:15:48 来源:oir作者:oir