How to Remove First and Last Element from Array in PHP

How to Remove First and Last Element from Array in PHP

If you have an array and you want to remove or delete the first element and last element from that array. So if you want to remove the first element then you have to use php array_shift() and if you want to remove the last element then you have to use php array_pop().

In this tutorial, you will learn how to use array_shift() and array_pop() to remove or delete the first and last element from array in PHP.

How to Remove First and Last Element from Array in PHP

By using the following ways, you can remove first and last elements from array in PHP:

  • Removing the First Element of an Array in PHP using Array_Shift()
  • Removing the Last Element of an Array in PHP using Array_pop()

Removing the First Element of an Array in PHP using Array_Shift()

PHP array_shift() function is used to remove the first element of an array in PHP. And it returns a new array.

Here is an example using array_shift() to remove first element from array in PHP:

$myArray = array('apple', 'banana', 'orange', 'pear');
array_shift($myArray);
print_r($myArray);

Output:

Array
(
    [0] => banana
    [1] => orange
    [2] => pear
)

Removing the Last Element of an Array in PHP using Array_pop()

PHP array_pop() function is used to remove the last element of an array in PHP. And it returns the new array.

Here is an example using array_pop() to remove last element from array in PHP:

$myArray = array('apple', 'banana', 'orange', 'pear');
array_pop($myArray);
print_r($myArray);

Output:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
)

Conclusion

Removing the first and last element of an array in PHP is a simple task that can be accomplished using the built-in array_shift() and array_pop() functions. By using these functions, you can easily manipulate arrays to suit your specific needs.

Recommended Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

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