0

For example, I want to take the value of myvalue in the following array without knowing its location :

$array = [
    "test" => "value", 
    "test_2" => [
        "test_3" => "values", 
        "test_4" => [
            "test_5" => [
                "myvalue" => "I need this"
            ]
        ]
    ]
];
brombeer
  • 8,716
  • 5
  • 21
  • 27
Parham
  • 3
  • 2

1 Answers1

1

You may want to use recursion for this. See this example for a demonstration. Outputs: string(11) "I need this"

<?php

// Your input array.
$array = ["test" => "value", "test_2" => ["test_3" => "values", "test_4" => ["test_5" => ["myvalue" => "I need this"]]]];

// Recursive function to get your value by key, independent of where it exists in your array.
function getValue(array $haystack, string $searchKey)
{
    // Loop through your input array.
    foreach ($haystack as $key => $value)
    {
        // If we find a node that is an array, descend into it.
        if (is_array($value))
        {
            echo "Descending into $key\n";
            // Recurse.
            return getValue($value, $searchKey);
        }
        else
        {
            // Leaf node found.
            echo "Reached end of tree at $key\n";
            
            // Is it our key?
            if ($key === $searchKey)
            {
                // Return it.
                echo "Found it: $value\n";
                return $value;
            }
        }
    }
}

var_dump(getValue($array, 'myvalue')); // string(11) "I need this"

Full output:

string(5) "value"
Reached end of tree at test
array(2) {
  ["test_3"]=>
  string(6) "values"
  ["test_4"]=>
  array(1) {
    ["test_5"]=>
    array(1) {
      ["myvalue"]=>
      string(11) "I need this"
    }
  }
}
Descending into test_2
string(6) "values"
Reached end of tree at test_3
array(1) {
  ["test_5"]=>
  array(1) {
    ["myvalue"]=>
    string(11) "I need this"
  }
}
Descending into test_4
array(1) {
  ["myvalue"]=>
  string(11) "I need this"
}
Descending into test_5
string(11) "I need this"
Reached end of tree at myvalue
Found it: I need this
string(11) "I need this"
Ro Achterberg
  • 2,504
  • 2
  • 17
  • 17