Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the position of an element in a simple array

Tags:

Let's say we have this array:

Array ( [0] => 10 [1] => 45 [2] => 23 ) 

How can I determine the position of element '45' in this array?

I'm using PHP.

Thank you.

like image 850
Psyche Avatar asked Sep 27 '10 13:09

Psyche


People also ask

How do you find a position of element in an array in Java?

In order to find the index of an element Stream package provides utility, IntStream. Using the length of an array we can get an IntStream of array indices from 0 to n-1, where n is the length of an array.

How do you find the position of an element in an array in Matlab?

In MATLAB the array indexing starts from 1. To find the index of the element in the array, you can use the find() function. Using the find() function you can find the indices and the element from the array. The find() function returns a vector containing the data.

What is a position in an array called?

An array index is an integer indicating a position in an array. Like Strings, arrays use zero-based indexing, that is, array indexes start with 0. The following displays the indexes and values in an array with 10 elements of type int. index.

How do you find the position of an array element in Python?

Use list. index() to find the position of an element in a list. Call list. index(value) to return the position of value in list .


2 Answers

Use array_search to get the key to a value:

$key = array_search(45, $arr);

And if you want to get its position in the array, you can search for the index of the key in the array of keys:

$offset = array_search($key, array_keys($arr));

So with an array like the following you will still get 1 as result:

$arr = array('foo' => 10, 'bar' => 45, 'baz' => 23);
like image 130
Gumbo Avatar answered Oct 08 '22 12:10

Gumbo


Google to the rescue: array_search

like image 23
Felix Kling Avatar answered Oct 08 '22 14:10

Felix Kling