How to add new item to array in PHP

Updated at 12-May-2021, By samar

How to add new item to array in PHP

Through the use of the programming language, we will work together to solve the "How to add new item to array in PHP" puzzle in this lesson.

You can add a new item to an array in PHP using the array_push method and you can also use key and value pair to add items to an associative array in PHP.
  • Add new item to index array using array_push method in PHP

    <?php
        $stack = array("orange", "banana");
        array_push($stack, "apple");
        print_r($stack);
    ?>
    

    You can add new items to an existing array using the array_push method. This method takes the first argument which is an existing array and after that, you can add new items to it as a comma-separated value.

  • Add new item to an associative array with key and value pair in PHP

    <?php 
        $array = array('foo' => 'bar'); 
        $array['title'] = 'blah';
        print_r($array);
    ?>
    

    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 the = 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.

Back to code snippet queries related php