php tutorial - PHP Add Element to Array - php programming - learn php - php code - php script




  • PHP array elements can be added manually or using PHP built-in array functions.

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”);
click below button to copy the code. php tutorial - team

  • 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

Sample Code

<?php  
 $web = array("PHP","HTML","CSS"); 
 array_push($web,"JavaScript","AJAX");  
  foreach($web as $lang){
       echo $lang." ";
  } 
?>
click below button to copy the code. php tutorial - team

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”);
click below button to copy the code. php tutorial - team

  • 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

Sample Code

<?php
 $web = array("PHP","HTML","CSS");
 array_unshift($web,"JavaScript","AJAX");
  foreach($web as $lang){
   echo $lang." ";
  }
?>
click below button to copy the code. php tutorial - team

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.

Related Searches to PHP Add Element to Array

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add wikitechy.com to your ad blocking whitelist or disable your adblocking software.

×