如何在foreach
循环中获取当前索引?如何在foreach循环中获取当前数组索引?
foreach ($arr as $key => $val)
{
// How do I get the index?
// How do I get the first element in an associative array?
}
如何在foreach
循环中获取当前索引?如何在foreach循环中获取当前数组索引?
foreach ($arr as $key => $val)
{
// How do I get the index?
// How do I get the first element in an associative array?
}
在示例代码,它只是$key
。
如果你想知道的,例如,如果这是第一个,第二个,或者我次迭代循环的,这是你唯一的选择:
$i = -1;
foreach($arr as $val) {
$i++;
//$i is now the index. if $i == 0, then this is the first element.
...
}
当然,这并未” t表示$val == $arr[$i]
,因为该数组可能是一个关联数组。
$key
是当前的数组元素的索引,和$val
是该数组元素的值。
第一元件具有0的索引因此,要访问它,使用
$arr[0]
为了得到阵列的第一个元素,使用此
$firstFound = false;
foreach($arr as $key=>$val)
{
if (!$firstFound)
$first = $val;
else
$firstFound = true;
// do whatever you want here
}
// now ($first) has the value of the first element in the array
$i = 0;
foreach ($arr as $key => $val) {
if ($i === 0) {
// first index
}
// current index is $i
$i++;
}
您也可以获得array_keys()
函数中的第一个元素。或array_search()
键的“索引”的关键。如果你在一个foreach
循环中,简单的递增计数器(由kip或cletus建议)可能是你最有效的方法。
<?php
$array = array('test', '1', '2');
$keys = array_keys($array);
var_dump($keys[0]); // int(0)
$array = array('test'=>'something', 'test2'=>'something else');
$keys = array_keys($array);
var_dump(array_search("test2", $keys)); // int(1)
var_dump(array_search("test3", $keys)); // bool(false)
这是最详尽的答案,到目前为止,并摆脱的需要一个$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>';
}
希望它可以帮助别人。
创建一个全新的数组长度“count($ array)”似乎很多避免引入一个标量变量的开销 – Kip 2014-12-30 20:32:12
array_keys对我来说是我的谢意! – MrWashinton 2016-04-18 15:55:05
foreach($array as $key=>$value) {
// do stuff
}
$关键是每个$阵列元素
不一定。如果你的数组看起来像这样:'$ array = array('cat'=>'meow','dog'=>'woof','cow'=>'moo','computer'=>'beep'); '第一项的$钥匙就是'猫'。 – 2015-12-03 17:05:49
感谢您的回复。 我认为指数将是关键。这里有:'猫','狗',... – 2015-12-04 04:44:14
我不明白为什么这不是这个页面上的最佳答案。 – 2015-12-17 22:14:10
很好的指标,因为这是第一个谷歌打了这个问题:
function mb_tell(&$msg) {
if(count($msg) == 0) {
return 0;
}
//prev($msg);
$kv = each($msg);
if(!prev($msg)) {
end($msg);
print_r($kv);
return ($kv[0]+1);
}
print_r($kv);
return ($kv[0]);
}
你可以得到的索引值与此
foreach ($arr as $key => $val)
{
$key = (int) $key;
//With the variable $key you can get access to the current array index
//You can use $val[$key] to
}
'$ key'是当前指数。 – jason 2009-09-20 03:12:03