0

I need a string to use it for a array pattern to find a value by this. for example

$test = ['test','test2' => ['test3','test4' => ['test5']]];
$pattern = "['test2']['test4']"
$response = $test{$pattern} <- search

give it a way to solve this ?

Pla558
  • 291
  • 5
  • 15

1 Answers1

1

Based on another question: Using a string path to set nested array data

function GetValueFromPattern($arr, $pattern) {
    $exploded = explode(".",$pattern);

    $temp = $arr;
    foreach($exploded as $key) {
        if(key_exists($key, $temp)) {
            $temp = $temp[$key];
        } else {
            return ["status" => false];
        }
    }
    return ["status" => true, "response" => $temp];
}

$test = ['test','test2' => ['test3'=>"a",'test4' => ['test5']]];
$pattern = "test2.test3";
$response = GetValueFromPattern($test, $pattern);
if ($response["status"]) {
    echo $response["response"];
} else {
    echo "Error!";
}
Coral Kashri
  • 3,436
  • 2
  • 10
  • 22
  • You'd definitely want to toss in `if(key_exists($key, $temp);) {} else {/* error stuff */}` – Sammitch May 31 '18 at 00:30
  • 1
    Note that you only need to use references if you want to assign to the result. Otherwise you can use normal assignment. – Barmar May 31 '18 at 00:30
  • Yeah you definitely don't want to return a reference from a "getter" and accidentally modify the array later. – Sammitch May 31 '18 at 00:31
  • You are right, my mistakes. The problems fixed, and I inserted the algorithm into a new function that will handle the procedure. – Coral Kashri May 31 '18 at 00:46