Saswat
Saswat

Reputation: 12836

How to shuffle an array in PHP so that all row are interchanged?

I have an array which is having video data ordered in descending order based on video likes. Here is my array:-

Array $video_order_list
(
    [0] => Array
        (
            [video_id] => 1
            [video_title] => A1
            [video_like] => 120
        )

    [1] => Array
        (
            [video_id] => 3
            [video_title] => A3
            [video_like] => 73
        )   

    [2] => Array
        (
            [video_id] => 2
            [video_title] => A2
            [video_like] => 63
        )

    [3] => Array
        (
            [video_id] => 4
            [video_title] => A4
            [video_like] => 55
        )

    [4] => Array
        (
            [video_id] => 5
            [video_title] => A5
            [video_like] => 40
        )       

    [5] => Array
        (
            [video_id] => 6
            [video_title] => A6
            [video_like] => 10
        )   

    [6] => Array
        (
            [video_id] => 7
            [video_title] => A7
            [video_like] => 3
        )
)

I am duplicating the array into another array:-

$random_list = $video_order_list;

Then I want to shuffle the array, for which I used this:-

shuffle($random_list);

However, there is a chance that my shuffled array could be like this:-

Array $random_list
(
    [0] => Array
        (
            [video_id] => 2
            [video_title] => A2
            [video_like] => 63
        )

    [1] => Array
        (
            [video_id] => 3
            [video_title] => A3
            [video_like] => 73
        )   

    [2] => Array
        (
            [video_id] => 7
            [video_title] => A7
            [video_like] => 3
        )

    [3] => Array
        (
            [video_id] => 4
            [video_title] => A4
            [video_like] => 55
        )

    [4] => Array
        (
            [video_id] => 6
            [video_title] => A6
            [video_like] => 10
        )

    [5] => Array
        (
            [video_id] => 5
            [video_title] => A5
            [video_like] => 40
        )       

    [6] => Array
        (
            [video_id] => 1
            [video_title] => A1
            [video_like] => 120
        )   
)

See that video_id = 4 is still in the 3rd index (4th position). How can I check such problem?

Upvotes: 0

Views: 33

Answers (1)

Shubham Kundu
Shubham Kundu

Reputation: 192

You may create a function checkArr() to check if any element in array is in same place or not and return false if not matched, and use shuffle() inside while loop keeping the condition as checkArr()

Upvotes: 1

Related Questions