tags:

views:

58

answers:

5

I have the following array

$group= array(
    [0] => 'apple',
    [1] => 'orange',
    [2] => 'gorilla'
);

I run the array group through an for each function and when the loop hits values of gorilla I want it to spit out the index of gorilla

foreach ($group as $key) {

    if ($key == gorilla){
        echo   //<------ the index of gorilla
    }

}
+1  A: 
foreach($group as $key => $value) {
    if ($value=='gorilla') {
        echo $key;
    }
}

The foreach($c as $k => $v) syntax is similar to the foreach($c as $v) syntax, but it puts the corresponding keys/indices in $k (or whatever variable is placed there) for each value $v in the collection.

However, if you're just looking for the index of a single value, array_search() may be simpler. If you're looking for indices for many values, stick with the foreach.

Amber
+2  A: 

You can use array_search function to get the key for specified value:

$key = array_search('gorilla', $group);
Sarfraz
Nice! Shortest way.
Pekka
@Pekka: You forgot about it but you had provided this function for a question few days back :)
Sarfraz
@Sarfraz yup, I was focused on the "how to get the current key in the loop" aspect :)
Pekka
+3  A: 
foreach( $group as $index => $value) {

if ($value == "gorilla")
 {
  echo "The index is: $index";
 }

}
Pekka
Though this is correct, I think use of the word 'key' is definitely wrong here. Indexes don't link to keys, they link to values ..
Matt
@Matt totally, I just copied the variable name without thinking. Corrected, cheers.
Pekka
A: 

Try this:

foreach ($group as $key => $value)
{
    echo "$key points to $value";
}

foreach documentation on php.net

matthew
+2  A: 

array_search — Searches the array for a given value and returns the corresponding key if successful

<?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;
?>
roddik