How to add a key value pair to existing array in laravel

Created at 19-Apr-2021 , By samar

How to add a key value pair to existing array in laravel

With this article, we’ll look at some examples of how to address the "How to add a key value pair to existing array in laravel" problem.

  • Add a key value pair to array using Array helpers method

    --PATH app\Http\Controllers\<YourController>.php
    //Before class definition
    use Illuminate\Support\Arr;
    
    //Inside controller's method
    $array = ['foo' => 'bar'];
    $array = Arr::add($array, 'price' , 100);
    
    //Before class definition
    use Illuminate\Support\Arr;
    
    //Real life example
    $product = Product::where('id', 1)->first();
    $product = Arr::add($product, 'price' , 100);
    

    This array method is the helper method which is used to add a new key value pair data to an existing array in laravel. You have to use use Illuminate\Support\Arr; before the class definition in your controller file and after that you can call the Array method.

    It adds the key and value to the array if the given key doesn't already exist in the array or is set to null. This code snippet has been tested on laravel 8.x and it’s working.

  • Add a new key and value pair to Array by specifying the key in brackets

    $arr = array(1 => 10, 2 => 20);
    $arr["x"] = 30;
    
    $arr = array(1 => 10, 2 => 20, 'x' =>25);
    $arr["x"] = 30;
    
    $post = Post::where('id', 1)->first();
    $post["new_key"] = 'New value';
    print_r($post->toArray());
    

    You can add a new key and value pair to an existing array by specifying the key in brackets and pass the value to this key using = operator. This method is very helpful if you have an array and you want to pass a new pair of data, or change the data by assigning the key and value to it. 

    It will change the data if the key already exists in it.

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.