Lets say i have this kind of code:
$array = [
'a'=> [
'b' => [
'c'=>'some value',
],
],
];
$array['a']['b']['c'] = 'new value';
Of course this is working, but what i want is to update this 'c' key using variable, something like that:
$keys = '[a][b][c]';
$array{$keys} = 'new value';
But keys are treatening as string and this is what i get:
$array['[a][b][c]'] = 'new value';
So i would like some help, to show me the right way to make this work without using eval().
By the way, there can be any number of array nests, so something like this is not a good answer:
$key1 = 'a';
$key2 = 'b';
$key3 = 'c';
$array[$key1][$key2][$key3] = 'new value';
Change Array Key using JSON encode/decode It's short but be careful while using it. Use only to change key when you're sure that your array doesn't contain value exactly same as old key plus a colon. Otherwise, the value or object value will also get replaced.
If you have a value and want to find the key, use array_search() like this: $arr = array ('first' => 'a', 'second' => 'b', ); $key = array_search ('a', $arr); $key will now contain the key for value 'a' (that is, 'first' ).
The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.
array is not set. This is also a predefined function in PHP which checks whether an index or a particular key exists in an array or not. It does not evaluate the value of the key for any null values. It returns false if it does not find the key in the array and true in all other possible cases.
It isn't the best way to define your keys, but:
$array = [];
$keys = '[a][b][c]';
$value = 'HELLO WORLD';
$keys = explode('][', trim($keys, '[]'));
$reference = &$array;
foreach ($keys as $key) {
if (!array_key_exists($key, $reference)) {
$reference[$key] = [];
}
$reference = &$reference[$key];
}
$reference = $value;
unset($reference);
var_dump($array);
If you have to define a sequence of keys in a string like this, then it's simpler just to use a simple separator that can be exploded rather than needing to trim as well to build an array of individual keys, so something simpler like a.b.c
would be easier to work with than [a][b][c]
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With