1

I want to get a random select from an array, but it does show other number that is not from my selected arrays.

<?php
$MainArray = array(
    'IC' => array(4,19,22,42,61,80,82,88),
    'IR' => array(9,12,17,45,46,67,68,89),
    'JP' => array(6,26,39,53,93),
    'DP' => array(1,8,14,35,38,59,70,71),
    'TA' => array(0,2,3,5,7,10,11,13,15,16,18,20,21,23,24,25,27,28,29,30,31,32,33,34,36,37,40,41,43,44,47,48,49,50,51,52,54,55,56,57,58,60,62,63,64,64,66,69,72,73,74,75,76,77,78,79,81,83,84,85,86,87,90,91,92,94,95,96,97,98,99)
);
$ArrayNumbers = array_merge($MainArray['IC'], $MainArray['IR'], $MainArray['TA'], $MainArray['DP']);
$setSelectedNumber = array_rand($ArrayNumbers);
if(in_array($setSelectedNumber, $MainArray['JP'])){
    echo 'ERROR FOUND: '.$setSelectedNumber;
}else{
    echo $setSelectedNumber;
}
?>

Am hoping to get a randomly match number from the merged arrays, but it also shows number from the JP array 6,26,39,53,93 which I don't want.

Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
Peter
  • 1,860
  • 2
  • 18
  • 47
  • Do you mean that you don't want to output a number from `$MainArray['JP']` AND you don't mind the `ERROR` or you want to avoid the `ERROR` completely and always have a successful result? Why merge that array into the master array, if you don't want it? What is the intent of your code? – mickmackusa Apr 19 '18 at 12:40
  • Possible duplicate of [Get random item from array](https://stackoverflow.com/questions/4233407/get-random-item-from-array) – mickmackusa Apr 19 '18 at 12:43
  • @mickmackusa i can always change the merge depending on how i want to use it – Peter Apr 19 '18 at 12:45

2 Answers2

2

array_rand returns a randomly picked key rather than value. You can get the value by this key as follows:

$setSelectedNumber = $ArrayNumbers[array_rand($ArrayNumbers)];
Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
1

Alex's answer is right. another possible solution using rand and array length to get a random key:

<?php
$MainArray = array(
 'IC' => array(4,19,22,42,61,80,82,88),
 'IR' => array(9,12,17,45,46,67,68,89),
 'JP' => array(6,26,39,53,93),
 'DP' => array(1,8,14,35,38,59,70,71),
 'TA' => array(0,2,3,5,7,10,11,13,15,16,18,20,21,23,24,25,27,28,29,30,31,32,33,34,36,37,40,41,43,44,47,48,49,50,51,52,54,55,56,57,58,60,62,63,64,64,66,69,72,73,74,75,76,77,78,79,81,83,84,85,86,87,90,91,92,94,95,96,97,98,99)
 );
 $ArrayNumbers = array_merge($MainArray['IC'], $MainArray['IR'], $MainArray['TA'], $MainArray['DP']);

 // select a random key of the array
 $randomKey = rand(0, count($ArrayNumbers) - 1)
 // Here you have a random Element
 $setSelectedNumber = $ArrayNumbers[$randomKey];


 if(in_array($setSelectedNumber, $MainArray['JP'])){
  echo 'ERROR FOUND: '.$setSelectedNumber;
 }else{
   echo $setSelectedNumber;
 }
 ?>

Happy Coding!

Sahith Vibudhi
  • 4,935
  • 2
  • 32
  • 34