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

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




Reffered: https://www.geeksforgeeks.org


Web Technologies

Related
How To Modify Content-Type in Postman? How To Modify Content-Type in Postman?
Guards in NestJS Guards in NestJS
How To Export Specific Request To File Using Postman? How To Export Specific Request To File Using Postman?
How to Handle Mouse and Keyboard Input in WebGL? How to Handle Mouse and Keyboard Input in WebGL?
How to Perform Statistical Calculations with math.js? How to Perform Statistical Calculations with math.js?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
25