0

So basically i would like to transform code like

$my_array = [];   
$cur_string = ['a', 'b', 'c', 'd'];
$v = 'Hello world!';

To something like:

$my_array['a']['b']['c']['d'] = $v;

I tried something like:

foreach( $cur_string as $cur ) {
    if ( !isset( $current[ $cur ] ) ) {
        $current[ $cur ] = [];
    }

    $current = $current[ $cur ];
}

$current[$k] = $v;

But I know this code isn't supposed to work.. How can I do this? I don't know exact level of nesting in $cur_string array.

2
  • Do you want to create that array structure or do you want to query an existing structure? Commented Mar 8, 2015 at 12:36
  • I mean something like "create if not exist" in array, you can see it in second piece of code i guess. Commented Mar 8, 2015 at 12:44

2 Answers 2

2

You can use the following method which is based on passing by reference.

/**
 * Fill array element with provided value by given path
 * @param array $data Initial array
 * @param array $path Keys array which transforms to path
 * For example, [1, 2, 3] transforms to [1][2][3]
 * @param mixed $value Saved value
 */
function saveByPath(&$data, $path, $value)
{
    $temp = &$data;

    foreach ($path as $key) {
        $temp = &$temp[$key];        
    }

    // Modify only if there is no value by given path in initial array
    if (!$temp) {
        $temp = $value;
    }

    unset($temp);
}

Usage:

Without initial value:

$a = [];

saveByPath($a, [1, 2, 3, 4], 'value');

var_dump($a[1][2][3][4]) -> 'value';

With initial value:

$a = [];
$a[1][2][3][4] = 'initialValue';

saveByPath($a, [1, 2, 3, 4], 'value');

var_dump($a[1][2][3][4]) -> 'initialValue';
Sign up to request clarification or add additional context in comments.

Comments

0

Showing both set and get functions:

$my_array = [];   
$cur_string = ['a', 'b', 'c', 'd'];
$cur_string2 = ['a', 'b', 'd', 'e'];
$v = 'Hello world!';
$v2 = 'Hello world2!';

function setValue(&$array, $position, $value) {
    $arrayElement = &$array;
    foreach($position as $index) {
        $arrayElement = &$arrayElement[$index];
    }
    $arrayElement = $value;
}

function getValue($array, $position) {
    $arrayElement = $array;
    foreach($position as $index) {
        if(!isset($arrayElement[$index])) {
            throw new Exception('Element is not set');
        }
        $arrayElement = $arrayElement[$index];
    }
    return $arrayElement;
}

setValue($my_array, $cur_string, $v);
setValue($my_array, $cur_string2, $v2);
var_dump($my_array);
try {
    $result = getValue($my_array, $cur_string);
} catch(Exception $e) {
    die($e->getMessage);
}
var_dump($result);

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.