How to Remove First and Last Element from Array in PHP

1. Using array_shift() and array_pop():

$arr = array(‘a’, ‘b’, ‘c’, ‘d’, ‘e’);

// Remove first element
array_shift($arr);

// Remove last element
array_pop($arr);

2. Using array_slice():

$arr = array(‘a’, ‘b’, ‘c’, ‘d’, ‘e’);

// Remove first element
$arr = array_slice($arr, 1);

// Remove last element
$arr = array_slice($arr, 0, -1);
[ad_1]

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

[ad_2]

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

GSTIN is 03EGRPS4248R1ZD.

Contact
Jassweb, Rai Chak, Punjab, India. 143518
Item added to cart.
0 items - 0.00