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

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including 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. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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