Question

I've splitted a string into array, giving a delimitator. So, this new array created, will contain values that I would want to use as indexes for another given array.

Having a situation like this:

// my given array
$array['key1']['key2']['a_given_key']['some_other_given_key'] = 'blablabl';

// the value of my given array
$value = $array['key1']['key2']['a_given_key']['some_other_given_key'];

$string = "key1;key2";
$keys = explode(";", $string);

I want to call dinamically (during the execution of my PHP script) the value of the given array, but, using as indexes all the values of the array $keys, and in addition appending the indexes ['a_given_key']['some_other_given_key'] of my given array.

I hope I have been clear.
Many thanks.

Était-ce utile?

La solution

To make it work you have to use references. Below code should work as you expect:

<?php

    $string = "key1;key2;key3;key4";
    $keys = explode(";", $string);


    $array['key1']['key2']['key3']['key4']['a_given_key']['some_other_given_key'] = 'blablabl';

    $ref = & $array;                               

    for ($i=0, $c = count($keys); $i<$c ; ++$i) {   
        $ref = &$ref[$keys[$i]];       
    }

    echo $ref['a_given_key']['some_other_given_key'];

    $value = $ref['a_given_key']['some_other_given_key'];

    echo $value;


?>

I would like to add that just after using reference you should unset it using:

unset($ref);

If you don't do this and many lines later you run for example $ref = 2; it will modify your source array so you have to remember about unsetting references just after it's no longer in use.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top