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

Using Temporary Variable

One of the simplest methods to swap the first and last elements of an array is to use a temporary variable. This method ensures that the values are swapped without losing any data.

Example: In this approach, we store the first element in a temporary variable, then assign the last element to the first position, and finally place the temporary variable’s value in the last position.

PHP
<?php

// Swap First and Last Array Elements
// using Temperory Variable
function swapElements(&$arr) {
    $n = count($arr);
    $temp = $arr[0];
    $arr[0] = $arr[$n - 1];
    $arr[$n - 1] = $temp;
}

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

Using List() and Array Destructuring

PHP 7 introduced array destructuring, which can be used to swap the first and last elements more succinctly.

Example: In this approach, the list() construct is used to swap the values directly. The elements are destructured and reassigned in a single statement, making the code more readable and concise.

PHP
<?php

// Swap First and Last Array Elements
// using Array Destructuring
function swapElements(&$arr) {
    $n = count($arr);
    
    list($arr[0], $arr[$n - 1]) = [$arr[$n - 1], $arr[0]];
}

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

Using Array Functions

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