arrays - PHP unique numbers and replace? -
we know rand(x,y) in php, not work unique numbers.
question 1: how can create 5 unique numbers 1-52, , save them array?
lets array are:
$foo = array(1,2,3,4,5);
and have secound array few of numbers in $foo:
$egg = array(1,5,4);
question 2: how can make function take , replace every number in $foo
new unique numbers, except numbers $egg
? ( make 2,3
new unique numbers).
(aka: values $egg
still there in $foo
every other value new)
1 question:
simply create range()
want unique random numbers. shuffle()
array , take array_slice()
it, this:
<?php $range = range(1, 52); shuffle($range); $randomnumbers = array_slice($range, 0, 5); print_r($randomnumbers); ?>
possible output:
array ( [0] => 25 [1] => 32 [2] => 7 [3] => 52 [4] => 35 )
2 question:
first difference both arrays array_diff()
. after create many random numbers range $diff
has elements. exclude numbers in $foo
array already, don't duplicates again.
then can array_combine()
numbers want replace random numbers.
and after go through array elements array_map()
, check if has replace or not, if yes return replaced number.
<?php $range = range(1, 52); $foo = [1, 2, 3, 4, 5]; $egg = [1, 5, 4]; $diff = array_diff($foo, $egg); $range = array_diff($range, $foo); shuffle($range); $replacement = array_combine($diff, array_slice($range, 0, count($diff))); $foo = array_map(function($v)use($replacement){ if(isset($replacement[$v])) return $replacement[$v]; return $v; }, $foo); print_r($foo); ?>
possible output:
array ( [0] => 1 [1] => 27 [2] => 10 [3] => 4 [4] => 5 )
Comments
Post a Comment