How can I get the current array index in a foreach loop?

前端 未结 10 1715
陌清茗
陌清茗 2020-12-14 06:19

How do I get the current index in a foreach loop?

foreach ($arr as $key => $val)
{
    // How do I get the index?
    // How do I get the fir         


        
10条回答
  •  南方客
    南方客 (楼主)
    2020-12-14 06:47

    You could get the first element in the array_keys() function as well. Or array_search() the keys for the "index" of a key. If you are inside a foreach loop, the simple incrementing counter (suggested by kip or cletus) is probably your most efficient method though.

    'something', 'test2'=>'something else');
       $keys = array_keys($array);
    
       var_dump(array_search("test2", $keys)); // int(1)     
       var_dump(array_search("test3", $keys)); // bool(false)
    

提交回复
热议问题