PHP array reverse

Question

Answers ( 1 )

    0
    2024-01-11T18:05:20+00:00

    It's asking about how to reverse the order of elements in an array using PHP.

    In PHP, you can reverse an array using the array_reverse() function. This function takes an array as input and returns a new array with the order of the elements reversed. Here's how you use it:

    Example Usage of array_reverse()

    // Define an array
    $originalArray = [1, 2, 3, 4, 5];
    
    // Reverse the array
    $reversedArray = array_reverse($originalArray);
    
    // Print the reversed array
    print_r($reversedArray);
    

    This code will output:

    Array
    (
        [0] => 5
        [1] => 4
        [2] => 3
        [3] => 2
        [4] => 1
    )
    

    Key Points:

    1. Function Used: array_reverse().
    2. Input: The original array.
    3. Output: A new array with the elements in reverse order.

    This function is the most straightforward way to reverse the order of an array in PHP. There are other, more complex methods, such as using loops, but array_reverse() is the simplest and most efficient for this specific task.

Leave an answer