VOOZH about

URL: https://www.geeksforgeeks.org/php/how-to-switch-the-first-element-of-an-arrays-sub-array-in-php/

⇱ How to Switch the First Element of an Arrays Sub Array in PHP? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Switch the First Element of an Arrays Sub Array in PHP?

Last Updated : 26 Jul, 2024

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.


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)

Comment
Article Tags:
Article Tags: