2

Assuming I give you the following array:

$array = array (
    array (
      'key' => 'value'
    ),
    array (
      'key' => 'another value'
    ),
    array (
      'key' => 'yet another value'
    ),
    array (
      'key' => 'final value'
    )
);

What I want from this array is the position of the array with the value supplied. So If I am searching $array for the value of "yet another value" the result should be: 2 because the matching array is at position 2.

I know to do the following:

foreach ($array as $a) {
    foreach ($a as $k => $v) {
        if ($v ===  "yet another value") {
            return $array[$a]; // This is what I would do, but I want
                               //  the int position of $a in the $array.
                               //  So: $a == 2, give me 2.
        }
    }
}

Update:

the key is always the same

3
  • is key always the same? Commented Jun 10, 2015 at 17:19
  • @n-dru yes the key is always the same Commented Jun 10, 2015 at 17:19
  • have you decided yet which answer is OK for you? :-) Commented Jun 16, 2015 at 11:19

4 Answers 4

4

You can simply do this, if the keys are the same:

$v = "yet another value";
$a = array_search(array("key"=>$v),$array);
echo $a;//2

http://sandbox.onlinephpfunctions.com/code/1c37819f25369725effa5acef012f9ce323f5425

Sign up to request clarification or add additional context in comments.

Comments

1
foreach ($array as $pos => $a) {
    foreach ($a as $k => $v) {
        if ($v ===  "yet another value") {
            return $pos;
        }
    }
}

This should be what you are looking for.

Comments

0

Since you want position of array then use count like:-

var count = 0;
foreach ($array as $a) {
    foreach ($a as $k => $v) {
        if ($v ===  "yet another value") {
            return count; 
        }
       count++;
    }
}

Comments

0

As you said that key is always the same, so you can declare a variable outside loop like so.

$position = 0;
foreach ($array as $a) {
    foreach ($a as $k => $v) {
        if ($v ===  "yet another value") {
            return $position;
        }
    }
    $position++;
}

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.