D
D
Donald_Duck2017-07-28 14:48:31
PHP
Donald_Duck, 2017-07-28 14:48:31

How to refer to an element of a multidimensional array in such cases?

Hello! Faced such problem: there is a line containing keys of an array. Using them, you need to get to the element in order to change / assign it. The key line looks something like this:

$keys = 'key1.key2.key3'; // Вложенность может быть любая

If you just need to get the value of the array, then there are no problems, but I can’t figure out how to change it in such cases.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tarex, 2017-07-28
@Donald_Duck

You can use assignment by reference.

<?php
$data = ['key1' => ['key2' => ['key3' => 123]]];

$keys = 'key1.key2.key3';
$keysArray = explode('.', $keys);

$element = &$data;
foreach ($keysArray as $key) {
    $element = &$element[$key];
}
$element = 321;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question