How to Add an Element to an Array in PHP

On this page, we will look at how to add an element to an array in PHP. Then, we will use each loop and the filter function to filter our output. It is not difficult to add an element to an array in PHP, but there are a few things you must keep in mind. First, you must create an array object. I will call the array() function to create a new instance of the array. Add the new element to the array. When you have a large array, you can also use the push(), pop(), and shift() functions to manage the elements of that array.

I am going to use the for loop to add our element. So let’s get started with that. I will now use the following code:

php append to array

$myArr = [1, 2, 3, 4];

array_push($myArr, 5, 8);
print_r($myArr); // [1, 2, 3, 4, 5, 8]

$myArr[] = -1;
print_r($myArr); // [1, 2, 3, 4, 5, 8, -1]

php add to array

$fruits = ["apple", "banana"];
// array_push() function inserts one or more elements to the end of an array
array_push($fruits, "orange");

// If you use array_push() to add one element to the array, it's better to use
// $fruits[] = because in that way there is no overhead of calling a function.
$fruits[] = "orange";

// output: Array ( [0] => apple [1] => banana [2] => orange )

php add item to array

<?php
  $z = ['me','you', 'he'];
  array_push($z, 'she', 'it');
  print_r($z);
?>

array_push in php

<?php
// Insert "blue" and "yellow" to the end of an array:


$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>

add item to array in php

<?php

$a=array("red","green");

array_push($a,"blue","yellow");

print_r($a);
?>

php add element to array

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