lov*_*ing 36 php syntax foreach
如何在foreach循环中获取当前索引?
foreach ($arr as $key => $val)
{
// How do I get the index?
// How do I get the first element in an associative array?
}
Run Code Online (Sandbox Code Playgroud)
Kip*_*Kip 58
在您的示例代码中,它只是$key.
如果你想知道,例如,如果这是循环的第一次,第二次或第 i 次迭代,这是你唯一的选择:
$i = -1;
foreach($arr as $val) {
$i++;
//$i is now the index. if $i == 0, then this is the first element.
...
}
Run Code Online (Sandbox Code Playgroud)
当然,这并不意味着$val == $arr[$i]因为数组可能是一个关联数组.
Fab*_*ert 15
到目前为止,这是最详尽的答案,并且不需要$i变量浮动.这是Kip和Gnarf答案的组合.
$array = array( 'cat' => 'meow', 'dog' => 'woof', 'cow' => 'moo', 'computer' => 'beep' );
foreach( array_keys( $array ) as $index=>$key ) {
// display the current index + key + value
echo $index . ':' . $key . $array[$key];
// first index
if ( $index == 0 ) {
echo ' -- This is the first element in the associative array';
}
// last index
if ( $index == count( $array ) - 1 ) {
echo ' -- This is the last element in the associative array';
}
echo '<br>';
}
Run Code Online (Sandbox Code Playgroud)
希望它可以帮助某人.
cle*_*tus 11
$i = 0;
foreach ($arr as $key => $val) {
if ($i === 0) {
// first index
}
// current index is $i
$i++;
}
Run Code Online (Sandbox Code Playgroud)
foreach($array as $key=>$value) {
// do stuff
}
Run Code Online (Sandbox Code Playgroud)
$ key是每个$数组元素的索引
小智 5
当前索引是 的值$key。对于另一个问题,您还可以使用:
current($arr)
Run Code Online (Sandbox Code Playgroud)
获取任何数组的第一个元素,假设您没有使用next(),prev()或其他函数来更改数组的内部指针。
| 归档时间: |
|
| 查看次数: |
114912 次 |
| 最近记录: |