如何在PHP找到 foreach 循环的索引?
foreach 构造提供了迭代数组元素的最简单方法。它适用于数组和对象。 foreach 循环虽然迭代了一个元素数组,但执行被简化并且相对而言在更短的时间内完成循环。它为索引迭代分配临时内存,这使得整个系统在内存分配方面具有冗余性能。如果我们尝试对未初始化的变量或具有不同数据类型的变量使用 foreach 循环,则会发出错误。
句法:
foreach( $array as $element ) {
// PHP Code to be executed
}
或者
foreach( $array as $key =>> $element) {
// PHP Code to be executed
}
返回值:
- $key:该变量保存当前元素的键索引/
- $value:在每次迭代中,将数组元素的当前值赋给 $value 变量。
方案一:
$value) {
echo "key = " . $key . ", value = "
. $value . "\n";
}
?>
输出:
key = 0, value = 1
key = 1, value = 2
key = 2, value = 3
key = 3, value = 4
key = 4, value = 5
key = 5, value = 6
key = 6, value = 7
key = 7, value = 8
key = 8, value = 9
key = 9, value = 10
方案二:
"Welcome",
"b" => "to",
"d" => "GeeksforGeeks"
);
// Iterate through the array using foreach
// construct and store the key and its value
// Use foreach loop to display the
// key of allelements
foreach ($arr as $key => $value) {
echo "key = " . $key . ", value = "
. $value . "\n";
}
?>
输出:
key = a, value = 1
key = b, value = 2
key = c, value = 3
key = d, value = 4
方案三:
$out) {
foreach($out as $keyIn => $value) {
echo "key = (" . $keyOut . ", " . $keyIn
. "), value = " . $value . "\n";
}
}
?>
输出:
key = (0, 0), value = 1
key = (0, 1), value = 2
key = (0, 2), value = 3
key = (1, 0), value = 4
key = (1, 1), value = 5
key = (1, 2), value = 6
key = (2, 0), value = 7
key = (2, 1), value = 8
key = (2, 2), value = 9