How to Switch the First Element of an Arrays Sub Array in PHP?
Last Updated :
26 Jul, 2024
Improve
Given a 2D array where each element is an array itself, your task is to switch the first element of each sub-array with the first element of the last sub-array using PHP.
Example:
Input: num = [
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i']
];
Output: [
['g', 'b', 'c'],
['d', 'e', 'f'],
['a', 'h', 'i']
]
Using a Temporary Variable
In this approach, we store the first element of the first sub-array in a temporary variable and then replace the first element of the first sub-array with the first element of the last sub-array and at last assign the value stored in the temporary variable to the first element of the last sub-array.
Example: Below is the implementation of the above approach to switch the first element of each sub-array in a multidimensional array.
<?php
// Define the array
$array = [
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i']
];
// Check if there are at least two sub-arrays
if (count($array) >= 2) {
// Store the first element
// of the first sub-array
$temp = $array[0][0];
// Switch the first element of the first
// sub-array with the first
// element of the last sub-array
$array[0][0] = $array[count($array) - 1][0];
$array[count($array) - 1][0] = $temp;
}
// Print the modified array
print_r($array);
?>
Output
Array ( [0] => Array ( [0] => g [1] => b [2] => c ) [1] => Array ( [0] => d [1] => e [2] => f ...
Time Complexity: O(1)
Auxiliary Space: O(1)