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.

1
  • 1
    Please don't post images of code! Commented Jul 26, 2023 at 19:03

1 Answer 1

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

                                    )

                            )

                    )

            )

    )

)

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

7 Comments

He has a dynamic string of indexes, not separate variables.
These 2 sign [ & ] can't from any variable value.
I know. But you can parse it into an array and then loop through the array, accessing the indexes dynamically. See the duplicate question.
Hmm, the idea is fine, form array element by processing intermediate keys. Can you please write 2/3 sample array elements?
Can't fit it into a comment.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.