Search code examples
phparrayslaravelmultidimensional-arrayarray-key

how to use string to be key of array in php


I have array that need to call.

$array['first_key']['second_key'] = 'value';

$keys = "['first_key']['second_key']";

I want to call it $array.$key that like $array['first_key']['second_key'].

Any one can help?


Solution

  • In Laravel, the easiest way to access nested dynamic array keys is by using the dot notation, ie first_key.second_key. Laravel's Illuminate\Support\Arr helper contains a method Arr::get that allows accessing nested array keys by using the dot notation. You can similarly also use Arr::set to set nested values using dot notation For example

    use Illuminate\Support\Arr;
    
    $key = 'first_key.second_key';
    
    $array['first_key']['second_key'] = 'value';
    // or
    Arr::set($array, $key, 'value');
    
    
    $value = Arr::get($array, $key);