php tutorial - PHP Delete Array Element - php programming - learn php - php code - php script



  • Array is an important and mostly used data type in PHP programming.
  • PHP programmer can add element to an array or delete element from an array manually with his/her own logical program but PHP also provides some built-in functions which help to delete array elements so easily.

Delete Array Last Element

  • PHP array_pop() function is used to delete the last element of an array. The structure of the array_pop() function is given below
array_pop($array_name);
click below button to copy the code. php tutorial - team

  • The array_pop() function only accepts the name of an array and then it will remove the last element of that array.
  • See below example where the array_pop() function is being used to remove the last element of an array

Sample Code

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

Output:

 PHP HTML CSS JavaScript
  • The example shows that the last element of $web array is being removed by array_pop() function and the remaining elements are being shown using foreach loop statement.

Delete Array First Element

  • PHP array_shift() function is used to remove the first element of an array. The structure of the array_shift() function is given below
array_shift($array_name);
click below button to copy the code. php tutorial - team

  • The array_shift() function only accepts the array name as an argument and then deletes the first element of that array.
  • See below example where the array_shift() function is being used to remove the first element of an array

Sample Code

<?php 
 $web = array("PHP","HTML","CSS");
 while(count($web)){
  $shift_element= array_shift($web); 
  print("Deleted: ".$shift_element." ");
  print("Now array contains: ".count($web)." element ");
 } 
?>
click below button to copy the code. php tutorial - team

Output

Deleted: PHP
Now array contains: 2 element
Deleted: HTML
Now array contains: 1 element
Deleted: CSS
Now array contains: 0 element
  • The example shows that the first element of $web array is being removed by the array_pop() function in every successful looping.

Related Searches to PHP Delete Array Element