How to add elements to the end of an array?
Answer: Using array_push()
Function
We can add elements to the end of the array using the array_push()
method. With the help of this function, we can add as many elements as we want, but all the elements will be added to the end of the element. The length of the array increases whenever a new element is added to the array.
We can add a string as well as the numeric value within the array.
Example: Using array_push()
function
In the given example, we have added an element PHP to the end of the array $proglang using the array_push()
function.
<!DOCTYPE html>
<html>
<head>
<title>Adding element to the end of the array</title>
</head>
<body>
<?php
$proglang = array("C", "C++", "Java", "JavaScript");
// Append array with new items
array_push($proglang, "PHP");
print_r($proglang);
?>
</body>
</html>
Output
Array ( [0] => C [1] => C++ [2] => Java [3] => JavaScript [4] => PHP )
Using square []
brackets
The most common method of adding elements to the end of the array using the square []
brackets. We can directly add the elements within the array without calling any function.
We just have to place the square brackets just after the array name and using the assignment (=) operator, we can assign the element to the array. Then this assigned element will be added to the end of the array.
Example: Using square []
brackets
In this example, we have added the element PHP to the end of the array $proglang using the square []
brackets.
<!DOCTYPE html>
<html>
<head>
<title>Adding element to the end of the array</title>
</head>
<body>
<?php
$proglang = array("C", "C++", "Java", "JavaScript");
$proglang[] = 'PHP';
var_dump($proglang);
?>
</body>
</html>
Output
array(5) { [0]=> string(1) "C" [1]=> string(3) "C++" [2]=> string(4) "Java" [3]=> string(10) "JavaScript" [4]=> string(3) "PHP" }
Conclusion
In this lesson, we have learned how to add elements at the end of the array in PHP. Here, we have discussed two approaches to add elements at the end of the array. First, we have used the pre-defined function array_push() to add elements to the end of the array. Using this function, we can add as many elements as we want to add. Then we have used the square brackets. Using square brackets, we can add elements without calling any function.