如何在 PHP 中找到 foreach 索引

  1. 使用 key 变量在 PHP 中查找 foreach 索引
  2. 使用 index 变量在 PHP 中查找 foreach 索引
  3. 同时使用 keyindex 变量在 PHP 中查找 foreach 索引

在本文中,我们将介绍查找 foreach 索引的方法。

  • 使用 key 变量
  • 使用 index 变量
  • 同时使用 keyindex 变量

使用 key 变量在 PHP 中查找 foreach 索引

变量键将每个值的索引存储在 foreach 循环中。PHP 中的 foreach 循环按如下方式使用。

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

变量值存储数组中每个元素的值。

<?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";
}   
?>

这里的关键变量包含 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

使用 index 变量在 PHP 中查找 foreach 索引

变量索引用作附加变量,以显示每次迭代中 foreach 的索引。

<?php 
// Declare an array 
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); 
$index = 0;

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

同时使用 keyindex 变量在 PHP 中查找 foreach 索引

现在,我们将同时使用 key 变量和附加变量 index 来查找 foreach 的索引。

<?php 
  
// Declare an array 
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); 
$index = 0;

foreach ($arr as $key=>$value) {    
    echo "The index is $index";
    $index = $key+1;
    echo "\n";
}
  
?>

我们已将 key 变量的值存储为索引 index 变量中其值的增量。这样,我们既可以使用 key 变量又可以使用 index 变量来查找 foreach 的索引。

输出:

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
comments powered by Disqus