Return the array position of the containig array

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

-------------Problems Reply------------

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

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.

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++;
}

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++;
}
}

Category:php Views:3 Time:2018-10-31
Tags: php arrays

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.166 (s). 11 q(s)