How to use Array Functions In PHP
We can also use PHP’s built-in array functions to achieve the swap.
Example: Here, we use array_shift() to remove the first element and array_pop() to remove the last element. We then use array_unshift() to add the last element to the beginning and array_push() to add the first element to the end. This method utilizes PHP’s array manipulation functions for clarity.
<?php
// Swap First and Last Array Elements
// using PHP Functions
function swapElements(&$arr) {
$n = count($arr);
$first = array_shift($arr);
$last = array_pop($arr);
array_unshift($arr, $last);
array_push($arr, $first);
}
// Driver code
$arr = [10, 20, 30, 40, 50];
swapElements($arr);
print_r($arr);
?>
Output
Array ( [0] => 50 [1] => 20 [2] => 30 [3] => 40 [4] => 10 )
Swipe First & Last Element of an Array in PHP
Swapping the first and last elements of an array is a common operation that can be useful in various scenarios, such as rearranging data or preparing it for specific algorithms.
Below are the approaches to swipe the first and last element of an array in PHP:
Table of Content
- Using Temporary Variable
- Using List() and Array Destructuring
- Using Array Functions