PHP - Getting the index of a element from a array

后端 未结 7 2122
既然无缘
既然无缘 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条回答
  •  时光取名叫无心
    2021-02-02 09:21

    PHP arrays are both integer-indexed and string-indexed. You can even mix them:

    array('red', 'green', 'white', 'color3'=>'blue', 3=>'yellow');
    

    What do you want the index to be for the value 'blue'? Is it 3? But that's actually the index of the value 'yellow', so that would be an ambiguity.

    Another solution for you is to coerce the array to an integer-indexed list of values.

    foreach (array_values($array) as $i => $value) {
      echo "$i: $value\n";
    }
    

    Output:

    0: red
    1: green
    2: white
    3: blue
    4: yellow
    

提交回复
热议问题