![]() |
VOOZH | about |
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']
]
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.
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)