Süleyman Kenar Süleyman Kenar - 6 months ago 31
PHP Question

PHP shuffle numerically indexed object array preserve key-value

I have array like this.

A=array();
A[0]=>name = "John";
A[0]=>lastname = "Blabla";
A[0]=>genre = "Male";
A[1]=>name = "Cheryl";
A[1]=>lastname = "Blabla";
A[1]=>genre = "Female";


I want to shuffle this array with preserving key-value pairs and without mixing every key. So basicly A[0] will be A[1](there are more than only 2 index just example it should be random) with all of child keys values etc.

How can i do this? Thanks

Answer

You can loop through the array and then randomly exchange the values in it.

for($x=0;$x<count($array);$x++){
    $temp=$array[$x];
    $index=rand(0,count($array)-1);
    $array[x]=$array[$index];
    $array[$index]=$temp;
}

Working example below.

<?php
$array=array();
$array[0]['name'] = "John";
$array[0]['lastname'] = "Blabla";
$array[0]['genre'] = "Male";
$array[1]['name'] = "Cheryl";
$array[1]['lastname'] = "Blabla";
$array[1]['genre'] = "Female";
$array[2]['name'] = "Amy";
$array[2]['lastname'] = "Blabla";
$array[2]['genre'] = "Female";
$array[3]['name'] = "Adam";
$array[3]['lastname'] = "Blabla";
$array[3]['genre'] = "Female";
$array[4]['name'] = "Hitan";
$array[4]['lastname'] = "Blabla";
$array[4]['genre'] = "Male";
$array[5]['name'] = "Mary";
$array[5]['lastname'] = "Blabla";
$array[5]['genre'] = "Female";

for($x=0;$x<count($array);$x++){
    $temp=$array[$x];
    $index=rand(0,count($array)-1);
    $array[$x]=$array[$index];
    $array[$index]=$temp;
}

var_dump($array);