0

I have an array like this:

<?php
$arr = [
    'a' => [
        'a1' => [
            'A11', 'A12', 'A13'
        ]
    ]
];

I can change the A13 element in an easy way:

$arr['a']['a1'][2] = 'A13 NEW';

But I want to do this with a function, something like this:

f($arr, ['a', 'a1', 2], 'A13 New');

I write this function using eval and I don't like it.

<?php
function f(&$array, $index, $value) {
    $e = '$array';
    for ($i = 0, $l = count($index); $i < $l; $i++) {
        $e .= '[$index[' . $i . ']]';
    }
    $e .= ' = $value;';

    // now we have `$e` like this
    // $array[$index[0]][$index[1]][$index[2]] = $value;

    eval($e);
}

How can I write this function without using eval?

1 Answer 1

3
$arr = array(
    'a' => array(
        'a1' => array(
            'A11', 'A12', 'A13'
        )
    )
);

function f(&$arr, $index, $value) {
    $tmp = &$arr;
    foreach ($index as $key) {
        $tmp = &$tmp[$key];
    }
    $tmp = $value;
}

f($arr, array('a', 'a1', 2), 'A13 New');

//$arr['a']['a1'][2] = 'A13 NEW';
var_dump($arr);
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.