0

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
    }

}

5 Answers 5

3

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

$key = array_search('gorilla', $group);
Sign up to request clarification or add additional context in comments.

2 Comments

@Pekka: You forgot about it but you had provided this function for a question few days back :)
yup, I was focused on the "how to get the current key in the loop" aspect :)
3
foreach( $group as $index => $value) {

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

}

2 Comments

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 totally, I just copied the variable name without thinking. Corrected, cheers.
2

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

Comments

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

Comments

0

Try this:

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

foreach documentation on php.net

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.