1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Answered Getting keys of multidimensional arrays

Discussion in 'Call of Duty: Black Ops 3 Answered Questions' started by request_method, Nov 15, 2016.

  1. request_method

    request_method New Member

    4
    1
    3
    Credits:
    39
    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?
    
     
  2. Cxwh

    Cxwh Active Member

    54
    33
    118
    Credits:
    1,190
    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: Feb 28, 2017
    CabCon and request_method like this.
  3. CabCon

    CabCon Head Administrator Staff Member Head Staff Team

    3,570
    2,287
    293
    Credits:
    104,477
    Thank you for the top answer. :y:
     
    Cxwh likes this.
  4. Cxwh

    Cxwh Active Member

    54
    33
    118
    Credits:
    1,190
    thanks :smile:
     
    CabCon likes this.

Related Content

  1. BunkerBaerIGER
  2. TotalModzHD
  3. TyNotTie
  4. JayCoder
  5. Alexisloic21

Share This Page