PHP Add Element to Array

PHP array elements can be added manually or using PHP built-in array functions. Adding array elements manually was explained in previous article. So, this article will explain how to add PHP array elements using PHP built-in array functions.

PHP Add Array Element

PHP Add Array Element

Add Element at the End of an Array

PHP array_push() function is used to add an element at the end of an array. The structure of  the array_push() function is given below…

array_push($array_name,”Element to add”);

The first argument of the array_push() function must be an array and other arguments will be  desired array elements. If the array already contains any element, the new element will be added at the end of that array.

See below example where the array_push() function is being used to add elements at the end of an array…

<?php  
 $web = array("PHP","HTML","CSS"); 
 array_push($web,"JavaScript","AJAX");  
  foreach($web as $lang){
       echo $lang." ";
  } 
?>

Output: PHP HTML CSS JavaScript AJAX

Here, two new elements are being added at the end of $web array and the array elements are being retrieved using foreach loop statement.

Add Element at the beginning of an Array

PHP array_unshift() is another built-in function which is used to add elements at the beginning of an array. The structure of the array_unshift() function is given below…

array_unshift($array_name,”Element to add”);

Like array_push() function, the first argument of array_unshift() function must be an array and other arguments are desired new array elements.

See below example where the array_unshift() function is being used to add elements at the beginning of an array…

<?php
 $web = array("PHP","HTML","CSS");
 array_unshift($web,"JavaScript","AJAX");
  foreach($web as $lang){
   echo $lang." ";
  }
?>

Output: JavaScript AJAX PHP HTML CSS

Here, two new elements are being added at the beginning of $web array and the elements are being retrieved using foreach loop statement.

Adding array elements using PHP built-in array function has been explained in this article. If you have any question about array_push() or array_unshift() function, feel free to contact with me from Contact us page. I’ll try my best to stay with you. Deleting PHP array element using built-in function will be explained in the next article. Spend some time to study the article and learn how to delete PHP array elements using PHP built-in array function.

2 Comments
  1. Benefits Of Coconut Oil
  2. plenty of fish dating site of free dating

Leave a Reply to plenty of fish dating site of free dating Cancel reply

Your email address will not be published. Required fields are marked *