PHP - Getting the index of a element from a array

后端 未结 7 2101
既然无缘
既然无缘 2021-02-02 08:40

How can I get the current element number when I\'m traversing a array?

I know about count(), but I was hoping there\'s a built-in function for getting the current field

7条回答
  •  -上瘾入骨i
    2021-02-02 09:42

    I recently had to figure this out for myself and ended up on a solution inspired by @Zahymaka 's answer, but solving the 2x looping of the array.

    What you can do is create an array with all your keys, in the order they exist, and then loop through that.

            $keys=array_keys($items);
            foreach($keys as $index=>$key){
                        echo "position: $index".PHP_EOL."item: ".PHP_EOL;
                        var_dump($items[$key]);
                        ...
            }
    

    PS: I know this is very late to the party, but since I found myself searching for this, maybe this could be helpful to someone else

提交回复
热议问题