如何在 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