0

I have a multidimensional associative array. Input to my program is a string that is compose of keys from the array separated by brackets. How can I target the array and update a value?

Input

$array = Array
(
    [store_name] => Jota
    [social] => Array
        (
            [fb] => foo

        )
)

$pattern = "[social][fb];"

$value = "bar";

Desired Output

$array = Array
(
    [store_name] => Jota
    [social] => Array
        (
            [fb] => bar
        )
)

I tried few attempts by using regex & variable reference but nothing is likely to be pasted here. You can say I am unable to think of an Idea to achieve this :(

1 Answer 1

1

You can use a regex to get the keys entered:

$pattern = '[social][fb]';
$matched = preg_match_all('/\[([^\[\]]+)\]/', $pattern, $keys);

This regex may look messy, but it's not that bad. It's just checking for any character (that isn't [ or ]) that's inside [].

Regex demo: https://regex101.com/r/Y0bw8f/1

Then you can loop over the found keys until you get to the end and then update the array value. This can be done by making a reference to the array and then moving it down for each key until you get to the value.

if ($matched !== false) {
    $arrayKeys = $keys[1];  // Get the 1st groups from the matched values
    $arrayPointer =& $array;  // Create a reference to the array

    foreach ($arrayKeys as $k) {
        $arrayPointer =& $arrayPointer[$k];  // Move the reference down each key
    }

    $arrayPointer = $value;  // Update the value
    unset($arrayPointer);  // Destroy the reference
}

var_dump($array);

Full code demo: Try it online!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.