Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php index of item

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')

like image 736
mcgrailm Avatar asked May 18 '11 15:05

mcgrailm


People also ask

What is an index in PHP?

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.

How do I change the index of an array element in PHP?

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.

What is Array_map function in PHP?

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.


2 Answers

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.

like image 91
Tufan Barış Yıldırım Avatar answered Sep 22 '22 17:09

Tufan Barış Yıldırım


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.

like image 27
Mihail Dimitrov Avatar answered Sep 19 '22 17:09

Mihail Dimitrov