benua benua - 2 months ago 6
PHP Question

Generating randomized pairs of elements in php

I want to generate random pairs of elements and have this code:

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

echo '<p>'.$myarray1[array_rand($myarray1)].'</p>';
echo '<p>'.$myarray2[array_rand($myarray2)].'</p>';
?>


but I get this as a result:

<p>3</p>
<p>2a</p>

or

<p>1</p>
<p>3a</p>

or

<p>2</p>
<p>1a</p>

etc.


and I want to only get certain pairs:

<p>2</p>
<p>2a</p>

or

<p>1</p>
<p>1a</p>

or

<p>3</p>
<p>3a</p>

etc.


how do I achieve that?

Answer

You should only call array_rand once only.

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

$rand = array_rand($myarray1); // assuming $myarray1 has the exactly same keys as $myarray2
echo '<p>'.$myarray1[$rand].'</p>'; 
echo '<p>'.$myarray2[$rand].'</p>'; 
?>

If they have different keys, you can try using array_values:

$myarray1 = ["a" => "1", "b" => "2", "c" => "3"];
$myarray2 = ["d" => "1a", "e" => "2b", "f" => "3c"];

$myarray1 = array_values($myarray1);
$myarray2 = array_values($myarray2);
$rand = array_rand($myarray1);
echo '<p>'.$myarray1[$rand].'</p>';
echo '<p>'.$myarray2[$rand].'</p>';

Please also refer to the documentation:

Comments