How to add new item to array in PHP

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.

Answers 2
  • Add new item to index array using array_push method in PHP

        $stack = array("orange", "banana");
        array_push($stack, "apple");

    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

        $array = array('foo' => 'bar'); 
        $array['title'] = 'blah';

    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