benua benua - 2 months ago 4
PHP Question

How to generate randomized pairs of elements in php without duplicates?

I'm trying to generate randomized pairs of elements:

<?
$myarray1=array('1','2','3');
$myarray2=array('a','b','c');

$key_rand = array_rand($myarray1);

echo '<p>'.$myarray1[$key_rand].'</p>';
echo '<p>'.$myarray2[$key_rand].'</p>';


$myarray1=array('1','2','3');
$myarray2=array('a','b','c');

$key_rand = array_rand($myarray1);

echo '<p>'.$myarray1[$key_rand].'</p>';
echo '<p>'.$myarray2[$key_rand].'</p>';


$myarray1=array('1','2','3');
$myarray2=array('a','b','c');

$key_rand = array_rand($myarray1);

echo '<p>'.$myarray1[$key_rand].'</p>';
echo '<p>'.$myarray2[$key_rand].'</p>';
?>


as a result I sometimes get duplicated pairs, which I don't want - for example:

2b
2b
3c

or

1a
1a
1a

I want to get only unique pairs each time, for example:

2b
1a
3c

or

1a
3c
2b

etc.

I'm probably doing it wrong, how do I fix that? Sorry new to this

Answer
$myarray1=array('1','2','3'); 
$myarray2=array('a','b','c'); 

$cnt=0;
$final = array();

while( $cnt<3 ) {
    $key_rand = array_rand($myarray1);
    $temp_arr = $myarray1[$key_rand].$myarray2[$key_rand];
    if( !in_array($temp_arr,$final) ) {
        $final[] = $temp_arr;
        $cnt++;
    }
}

echo "<pre>";
print_r($final);

output:

Array
(
    [0] => 3c
    [1] => 1a
    [2] => 2b
)

generate random pairs with while and push into an array and check if exists with in_array to be uniq

if you have an array with 2 elements and $cnt>2 ... will be an infinite loop

Late added by @benua "great, but I need to insert the output into html like that: c a b is it possible?"

$myarray1=array('1','2','3'); 
$myarray2=array('a','b','c'); 

$cnt=0;
$final = array();

while( $cnt<3 ) {
    $key_rand = array_rand($myarray1);
    if( !in_array($key_rand,$final) ) {
        $final[] = $key_rand;
        $cnt++;
    }
}

$links = array();
foreach( $final as $key ) {
    $links[] = "<a href='".$myarray1[$key]."'>".$myarray2[$key]."</a>";
}

echo "<pre>";
print_r($links);


<pre>Array
(
    [0] => <a href='1'>a</a>
    [1] => <a href='3'>c</a>
    [2] => <a href='2'>b</a>
)