Skip to content
Advertisement

Php random odd or even [closed]

I want him to randomly pick 5 numbers from the string I entered and check them to see if they’re even or odd This is the code I made but I don’t want 0 included:

    <?php
$s = array();
$tek =array();
$cift =array();
$tamsayi = array(1,2,3,4,5,6,7,8,9,10);

for( $i=0; $i<5; $i++){

    $s [$i]= array_rand($tamsayi);
}
echo "Oluşturulan rastgele dizi : ";
  foreach ($s as $el) {
    echo $el;
  }
  for($j = 0; $j<5;$j++){
      if($s[$j] % 2 == 0){
        $cift[$j]=$s[$j];
      }else{
          $tek[$j]= $s[$j];
      }
  }
  echo '<br>';
  echo "Çift sayılar : ";
  echo '<br>';
  foreach ($cift as $eli) {
    echo $eli;
    echo '<br>';
  }
  echo "Tek sayılar : ";
  echo '<br>';
  foreach ($tek as $elin) {
    echo $elin;
    echo '<br>';
  }
?>

Advertisement

Answer

Try this:

<?php
$array = [1,2,3,4,5,6,7,8,9,10];
$finalArray = [];

for($i = 0; $i < 5; $i++) {
    $key = array_rand($array);
    $random = $array[$key];
   if($random % 2 == 0){
       $finalArray["even"][] = $random;
   } else {
       $finalArray["odd"][] = $random;
   }
}   
print("<pre>".print_r($finalArray,true)."</pre>");

?>

Output will look smth like this:

Array
(
    [even] => Array
        (
            [0] => 4
            [1] => 4
            [2] => 8
        )

    [odd] => Array
        (
            [0] => 9
            [1] => 3
        )

)

And if you want number to appear only once:

<?php

$array = [1,2,3,4,5,6,7,8,9,10];
$finalArray = [];

for($i = 0; $i < 5; $i++) {
    $key = array_rand($array);
    $random = $array[$key];
    unset($array[$key]);
   if($random % 2 == 0){
       $finalArray["even"][] = $random;
   } else {
       $finalArray["odd"][] = $random;
   }

}   
print("<pre>".print_r($finalArray,true)."</pre>");

?>

Which will print allways unique values, like: Array

(
    [odd] => Array
        (
            [0] => 3
            [1] => 5
            [2] => 7
        )

    [even] => Array
        (
            [0] => 4
            [1] => 10
        )

)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement