Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Getting the index of a element from a array

Tags:

arrays

php

field

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 index too, without having to add a extra counter variable.

like this:

foreach($array as $key => value)   if(index($key) == count($array) .... 
like image 965
Alex Avatar asked Sep 21 '10 21:09

Alex


People also ask

How do I extract an index from an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.

Can you access an element in an array by using its index?

You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

What is array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.

How do you find a specific value in an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.


2 Answers

You should use the key() function.

key($array) 

should return the current key.

If you need the position of the current key:

array_search($key, array_keys($array)); 
like image 134
Zahymaka Avatar answered Sep 24 '22 02:09

Zahymaka


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 
like image 20
Bill Karwin Avatar answered Sep 26 '22 02:09

Bill Karwin