How to use List() and Array Destructuring In PHP
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
// 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 )
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