jamus
1
Hi,
I grabbing a random value from 2 separate arrays, like so:
<?php
$vertical = array("top", "bottom");
$vert_props = array_rand($vertical, 2);
$horizontal = array("left", "right");
$hori_props = array_rand($horizontal, 2);
?>
<?php echo $vertical[$vert_props[0]] . ' and ' . $horizontal[$hori_props[1]]; ?>
Is this the best way of doing this? I also need to call this several times from within a for each loop - so each loop gets random values each time.
jamus
2
$vert_props = array_rand($vertical, 2);
$hori_props = array_rand($horizontal, 2);
echo $vertical[$vert_props[0]] . ' and ' . $horizontal[$hori_props[1]];
Moving the array_rand inside the "for each’ gives me random elements each call but Im still not sure this is the best way of doing this?
If you’re just wanting to pull out /1/ random value from each array
$a1 = array("a", "b", "c", "d");
$a2 = array("z", "y", "x", "w");
foreach ($array as $value) {
$randoms = array(array_rand($a1), array_rand($a2));
echo $randoms[0]." and ".$randoms[1];
}
If you’re wanting to pull /1/ random value out of each array but don’t want them being called again…
$a1 = array("a", "b", "c", "d");
$a2 = array("z", "y", "x", "w");
foreach ($array as $value) {
shuffle($a1);
shuffle($a2);
$randoms = array($a1[0], $a2[0]);
echo $randoms[0]." and ".$randoms[1];
array_shift($a1);
array_shift($a2);
}