reverse array in PHP

Question

Answers ( 1 )

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

    To reverse an array in PHP, you can use the array_reverse() function.

    The array_reverse() function takes an array as input and returns a new array with the elements in reverse order. It's important to note that the keys are preserved if the second parameter is set to true.

    Here's an example:

    <?php
    $originalArray = array(1, 2, 3, 4, 5);
    
    // Reverse the array
    $reversedArray = array_reverse($originalArray);
    
    // Output the reversed array
    print_r($reversedArray);
    ?>
    

    This will output:

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

    If you want to maintain key associations, you can do so by passing true as the second argument to array_reverse():

    $reversedArrayWithKeys = array_reverse($originalArray, true);
    

    This function is generally the simplest and most straightforward way to reverse an array in PHP. However, if you have specific requirements (like reversing the array in-place without using additional memory), you might need a custom implementation.

Leave an answer