PHP で foreach インデックスを見つける方法
Minahil Noor
2023年1月30日
PHP
PHP Foreach
-
PHP で forkey インデックスを見つけるために
key変数を使用する -
PHP で forindex インデックスを見つけるために
index変数を使用する -
PHP で
foreachインデックスを見つけるためにkeyとindex変数の両方を使用する
この記事では、foreach インデックスを見つける方法を紹介します。
key変数を使用するindex変数を使用するkeyとindex変数の両方を使用する
PHP で forkey インデックスを見つけるために key 変数を使用する
変数キーは、各値のインデックスを 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";
}
?>
ここでの $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 で forindex インデックスを見つけるために index 変数を使用する
変数インデックスは、各反復での 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
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 変数の値をインクリメントしてインデックス変数に格納しました。このように、$key 変数とインデックス変数の両方を使用して、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
チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe