0
<?php
$array['a']['b']['c']['d'] = "foo";
$many = ['b']['c'];

echo $array['a']$many['d'];
?>

Is there any way to make this work?

I have try with {} around but i cannot make it work. The goal i try to achieve is to replace b and c cause I have ['a']['children']['b']['children']['c']['d'].

Since i can have many children i want a way to avoid to write it every time dans replace ['children']['b']['children']['c'] as a variable cause A and D will always by there.

SimonMayer
  • 4,719
  • 4
  • 33
  • 45
  • 1
    Please don't post [images of code](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question)! – brombeer Jul 26 '23 at 19:03

1 Answers1

0

You can't write braces("[", "]") as a variable value.

I'm not sure, it'll help you or not, the intermediate keys are sending here seperated by underscore as 2nd param, the 3rd is the value,

<?php

$array = array('a' => array());

setArrVal($array['a'], 'b_children_c_childs', 'Argentina');

//echo '<pre>';print_r($array);echo '</pre>';

function setArrVal(&$array, $indexes, $value)
{
    $index = explode('_', $indexes);
    
    $temp =& $array;
    foreach ($index as $i)
    {
        $temp[$i] = array();
        $temp =& $temp[$i];
    }

    $temp['d'] = $value;
}
?>

The array structure will be:

Array (

[a] => Array

    (

        [b] => Array

            (

                [children] => Array

                    (

                        [c] => Array

                            (

                                [childs] => Array

                                    (

                                        [d] => Argentina

                                    )

                            )

                    )

            )

    )

)

Kajal Pasha
  • 104
  • 3