I have an array that looks like this:
$fruit = array('apple','orange','grape');
How can I find the index of a specific item, in the above array? (For example, the value 'orange')
PHP indexed array is an array which is represented by an index number by default. All elements of array are represented by an index number which starts from 0. PHP indexed array can store numbers, strings or any object. PHP indexed array is also known as numeric array.
We will use array_values() function to get all the values of the array and range() function to create an array of elements which we want to use as new keys or new index of the array (reindexing). Then the array_combine() function will combine both the array as keys and values.
The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.
Try the array_search function.
From the first example in the manual:
<?php $array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red'); $key = array_search('green', $array); // $key = 2; $key = array_search('red', $array); // $key = 1; ?>
A word of caution
When comparing the result, make sure to test explicitly for the value false
using the ===
operator.
Because arrays in PHP are 0-based, if the element you're searching for is the first element in the array, a value of 0 will be returned.
While 0 is a valid result, it's also a falsy value, meaning the following will fail:
<?php $array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red'); $key = array_search('blue',$array); if($key == false) { throw new Exception('Element not found'); } ?>
This is because the ==
operator checks for equality (by type-juggling), while the ===
operator checks for identity.
have in mind that, if you think that your search item can be found more than once, you should use array_keys() because it will return keys for all matching values, not only the first matching key as array_search().
Regards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With