ArdaTahsinAyar ArdaTahsinAyar - 1 month ago 10
PHP Question

PHP How To Find the Keys of A Value In Multidimensional Array

I have been working on this problem, but i have had no result with current functions of PHP.

I have a multidimensional array, like:

Array
(
[3] => Array
(
[16] => 0
[17] => 1
[18] => 2
)

[4] => Array
(
[22] => 3
[23] => 4
)

[5] => Array
(
[1] => 5
)

)


If the first keys of array were static, it would have been easy to fix, but
all the keys are dynamical data. (3, 4, 5 etc...). I like to have a function that finds the keys of a value.

myFunction($myArray, 3) // 3 = my value.


If there is a value "3", I want function to give me the keys of it. (4, 22). Just like the array on the top.

Thanks in advance.

Answer

Suppose you want an array of keys with the index of the array which contains the searched value (3), and the index of the 3 value in that array, this should works:

$matched = [];
foreach($object as $extIndex => $array){
    foreach($array as $intIndex => $value){
        if($value == 3){
            $matched[] = [$extIndex, $intIndex];
        }
    }
}
var_dump($matched);

edit: $object is the object as described in the question.