Answered Getting keys of multidimensional arrays

request_method

New Member
Messages
4
Reaction score
1
Points
3
How do I get the key of an array when the array is multidimensional and I only have the value?

Code:
function createTestArray()
{
    //our arrays
    childArray1 = array(
        "val 1",
        "val 2"
    );
    childArray2 = array(
        "val 3",
        "val 4"
    );
    self.parentArray = array(
        "val 5",
        "val 6",
        childArray1,
        childArray2
    );
}

//Now how do I get the key when I only know the value?
 

Cxwh

Veteran
Messages
64
Reaction score
45
Points
793
I am not 100% sure as to what you mean, but I think this is what you're looking for:
Code:
function searchArrayKey(Array, value)
{
    foreach(key, val in Array)
    {
        if(value == val)
            return key;
        if(isArray(val))
            return searchArrayKey(val, value);
    }
    return false;
}

I tested it in php and it worked, but note:
If you have if multiple keys returning the same value, only the first one of them will be returned
PHP:
<?php
$_69 = ["6", "9"];
$_911 = ["9", "1", "1"];
$testArray = ["Bush", "did", $_69, $_911];
function searchArrayKey($arr, $value)
{
    foreach($arr as $key => $val)
    {
        if($val == $value) //or $var === $value if you want them to be identical
            return $key;
        if(is_array($val))
            return searchArrayKey($val, $value);
    }
    return false;
}
echo searchArrayKey($testArray, "9") . "<br/>"; //output -> 1 | var_dump will return "1"
?>
 
Last edited:

CabCon

Head Administrator
Staff member
Head Staff Team
Messages
4,998
Reaction score
2,918
Points
1,053
I am not 100% sure as to what you mean, but I think this is what you're looking for:
Code:
function searchArrayKey(Array, value)
{
    foreach(key, val in Array)
    {
        if(item == val)
            return key;
        if(isArray(val))
            return searchArrayKey(val, value);
    }
    return false;
}

I tested it in php and it worked, but note:
If you have if multiple keys returning the same value, only the first one of them will be returned
PHP:
<?php
$_69 = ["6", "9"];
$_911 = ["9", "1", "1"];
$testArray = ["Bush", "did", $_69, $_911];
function searchArrayKey($arr, $value)
{
    foreach($arr as $key => $val)
    {
        if($val == $value) //or $var === $value if you want them to be identical
            return $key;
        if(is_array($val))
            return searchArrayKey($val, $value);
    }
    return false;
}
echo searchArrayKey($testArray, "9") . "<br/>"; //output -> 1 | var_dump will return "1"
?>
Thank you for the top answer. :y:
 
Top