Search code examples
phparrayssliderextractsplice

PHP - Extract first 3 elements of an array -> Shuffle it -> and add them back to the orig. array


is it possible to "extract" the first 3 elements of an array, then shuffle this 3 elements and add them back to the array?

It's a slider and the first 3 slides should be random displayed on every pageload ...

Could someone help?

 public function shuffle( $data ) {

    // Return early there are no items to shuffle.
    if ( ! is_array( $data['slider'] ) ) {
        return $data;
    }

    // Prepare variables.
    $random = array();
    $keys   = array_keys( $data['slider'] );

    // Shuffle the keys and loop through them to create a new, randomized array of images.
    shuffle( $keys );
    foreach ( $keys as $key ) {
        $random[$key] = $data['slider'][$key];
    }

    // Return the randomized image array.
    $data['slider'] = $random;
    return $data;

}

/* ----------------------- UPDATE ----------------------- */

This is how it works for me, but why? Im relative new to php ;D

public function shuffle($data) {

    // Return early there are no items to shuffle.
    if (!is_array($data['slider'])) {
        return $data;
    }

    $sliced_array = array_slice($data["slider"], 0, 3, TRUE);
    // Shuffle the keys and loop through them to create a new, randomized array of images.
    shuffle($sliced_array);


    $data['slider'] = $sliced_array + array_slice($data["slider"], 0);

    return $data;
}

Solution

  • Yes, its possible. You were on right track. With a few tweaks it worked well.

    Code:

    public function shuffling($data) {
    
        // Return early there are no items to shuffle.
        if (!is_array($data['slider'])) {
            return $data;
        }
    
        $sliced_array = array_slice($data["slider"], 0, 3, TRUE);
        // Shuffle the keys and loop through them to create a new, randomized array of images.
        shuffle($sliced_array);
    
        foreach ($sliced_array as $key => $value) {
            $data['slider'][$key] = $value;
        }
        return $data;
    }
    

    I've tried with sample array like:

    shuffling(["slider" => [
            0 => "A",
            1 => "B",
            2 => "C",
            3 => "D",
            4 => "E",
    ]]);
    

    And result is:

    Array
    (
        [slider] => Array
            (
                [0] => B
                [1] => C
                [2] => A
                [3] => D
                [4] => E
            )
    
    )
    

    Note: shuffle is already function defined in php. That's why I've changed name to shuffling.