php index of item

PhpArraysIndexing

Php Problem Overview


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 Solutions


Solution 1 - Php

Try the array_search function.

From the first example in the manual:

> $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.

Solution 2 - Php

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.

Solution 3 - Php

You have to use array_search.

Look here http://www.php.net/manual/en/function.array-search.php

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmcgrailmView Question on Stackoverflow
Solution 1 - PhpTufan Barış YıldırımView Answer on Stackoverflow
Solution 2 - PhpMihail DimitrovView Answer on Stackoverflow
Solution 3 - PhpNicola PeluchettiView Answer on Stackoverflow