MuthaFury MuthaFury - 8 days ago 7
PHP Question

2 different array with different values

My question may sound abit silly, but I know it is possible to do. I'm actually trying to make the array from mysql to be different from the array I have

shuffle
it already. I want to maintain the array keys, just the value in different order.

Here is the example,

Array from MYSQL:-

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


Array after
shuffle
:-


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


If you notice,
MYSQL array
key 3 has the same value as
shuffle array
, I want it to be different. How can I do so?

Here is my code:-

function get_random_elements($array) {
$ori_array = $array;

echo "<pre>";
print_r($ori_array);
echo "</pre>";

shuffle($array);

echo "<pre>";
print_r($array);
echo "</pre>";

for($x=0; $x<count($array); $x++) {
if ($array[$x] == $ori_array[$x])
{
$dupliarray[] = "Array value: ".$array[$x]." Key :".$x;
unset($array[$x]);
}

}

echo "<pre>";
print_r($dupliarray);
echo "</pre>";

}

$mysql_array = array(0=>'1',1=>'2',2=>'3',3=>'4',4=>'5',5=>'6',6=>'7',7=>'8');

get_random_elements($mysql_array);

Answer

One solution can be to shuffle array until it became totally differ from source array:

$sourceArray = [0, 1, 2, 3, 4, 5, 6, 7, 8];
$shuffledArray = $sourceArray; //because function shuffle will change passed array

shuffle($shuffledArray);    
while (count(array_intersect_assoc($sourceArray, $shuffledArray))) {
    shuffle($shuffledArray);
}

echo '<pre>';
var_dump($sourceArray, $shuffledArray);