PHP Delete Array Element

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. This article will show how to delete array element using PHP built-in functions.

PHP Delete Element from Array

PHP Delete Element From Array

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);

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…


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

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);

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…


<?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 ");
 } 
?>

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.

Removing array elements using PHP built-in array function has been explained in this article. If you face any problem to understand this article, feel free to contact with me from Contact us page. I’ll try my best to stay with you. Sorting PHP array elements will be explained in the next article. Spend some time to study the article and learn how to sort PHP array element.

Leave a Comment

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