简体   繁体   中英

Even and Odd numbers sorting into Text file

HI Everyone I need help in sorting out even and odd numbers. The numbers are entered in a form and are called to the php file ( at bottom) after which I need to display them in a text file this part for me is all good. I am having trouble separating the numbers even from odd. I know we need to use the modulus command but I don't know exactly how to place it in the loop.

    $valOne = $_GET["value1"];
    $valTwo = $_GET["value2"];
    $valThr = $_GET["value3"];
    $valFou = $_GET["value4"];
    $valFiv = $_GET["value5"];
    $valSix = $_GET["value6"];
    $valSev = $_GET["value7"];
    $valEig = $_GET["value8"];
    $valNine = $_GET["value9"];
    $valTen = $_GET["value10"];

    $myFile = "test.txt";
    $fh = fopen($myFile, 'w') or die("can't open file");
    $array1= array ($valOne, $valTwo, $valThr, $valFou,$valFiv,
                $valSix,$valSev,$valEig,$valNine,$valTen);
    foreach($array1 as $key => $value){
    fwrite($fh, $value. "\t");


    }
    fclose($fh);

what you want is

if ($number % 2 == 0) {
    // even number
}
else
{
    // odd
}

in your case

foreach($array1 as $key => $value){
    if ($value % 2 == 0) {
         fwrite($fh, $value. "\t");
    }
}

seperate even and odd numbers in one file

$even = array_filter($array1, function($number) { return $number % 2 == 0; });
$odd = array_filter($array1, function($number) { return $number % 2 == 1; });

$max = max(count($even), count($odd));
for ($i = 0; $i < $max; $i++) {
    $n1 = isset($even[$i]) ? $even[$i] : "";
    $n2 = isset($odd[$i]) ? $odd[$i] : "";

    fwrite($fh, str_pad($n1, 20, STR_PAD_RIGHT) . $n2);
}
foreach($array1 as $key => $value)
{
   $myvar = ($value %2 == 0 ? '$value' : '' );
   fwrite($fh, $myvar . "\t");
}

try the following

 $valOne = $_GET["value1"];
$valTwo = $_GET["value2"];
$valThr = $_GET["value3"];
$valFou = $_GET["value4"];
$valFiv = $_GET["value5"];
$valSix = $_GET["value6"];
$valSev = $_GET["value7"];
$valEig = $_GET["value8"];
$valNine = $_GET["value9"];
$valTen = $_GET["value10"];

$myFile = "test.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$array1= array ($valOne, $valTwo, $valThr, $valFou,$valFiv,
            $valSix,$valSev,$valEig,$valNine,$valTen);
foreach($array1 as $key => $value){
  if($value%2==0)
   {
     fwrite($fh, $value. "\t");
      }
    else
    {
      //write your own code..
       }

}
fclose($fh);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM