How to use array_push in php

In PHP, the array_push() function is used to add one or more elements to the end of an array. Here is an example of how to use array_push() in PHP:

php
<?php
$my_array = array("apple", "banana", "orange");

// Adding a single element to the end of the array
array_push($my_array, "pear");

// Adding multiple elements to the end of the array
array_push($my_array, "grape", "watermelon");

print_r($my_array);
?>

In this example, we start with an array $my_array that contains three elements: “apple”, “banana”, and “orange”. We then use array_push() to add a single element (“pear”) to the end of the array, followed by two more elements (“grape” and “watermelon”).

The array_push() function takes two arguments: the array you want to add elements to, and the element or elements you want to add. You can add one or more elements to the array by including them as additional arguments.

It’s important to note that array_push() always adds elements to the end of the array, regardless of their original index. If you want to add an element to a specific index in the array, you can use the array assignment syntax, like so:

php
<?php
$my_array = array("apple", "banana", "orange");

// Adding an element to a specific index in the array
$my_array[1] = "pear";

print_r($my_array);
?>

In this example, we are assigning the value “pear” to the second element in the array (index 1), effectively replacing the original value (“banana”) with the new value.