How to Insert an Element to The End of an Indexed Array in PHP?

How to Insert an Element to The End of an Indexed Array in PHP?

  • PHP
  • 1 min read

This tutorial explains, how to insert an element to the end of an indexed array in PHP.

In PHP, there is a predefined function array_push(), which will help us to insert an element to the end of an array.

Here is an example for inserting an element with value "John" to the end of an array $a.

<html>
<body>
<?php
$a=array("John","tarak","mona","rajat");
array_push($a,"John");
for($i=0;$i<count($a);$i=$i+1)
{
echo $a[$i]."<br>";
}

?>
</body>
</html>

Output:

John
tarak
mona
rajat
John

Here the array $a is containing 4 elements. "john" is assigning as an array element value to the end of the array.

After adding the element, the present array elements are:

Here $a[0]="shilu"=first array element value.
$a[1]="tarak"=second array element value.
$a[2]="mona"=third array element value.
$a[3]="rajat"=fourth array element value.
$a[4]="john"=fifth array element value.

Finally, we have printed the array element values with different lines using for loop and echoed statement and <br> tag.