Thursday, 28 June 2012

Determine Odd And Even Numbers In Php

The user will input a series of numbers and the program will determine if odd or even numbers.


Source Code:
01<?php
02  $odd  "";
03  $even "";
04  if(isset($_POST['check']) && trim($_POST['check']) != "") {
05    $numbers explode(",", trim($_POST['number']));
06    //looping tru array
07    for($x = 0;$x count($numbers);$x++) {
08      if (($numbers[$x]%2) == 0) {
09        if($even == "") {
10          $even $numbers[$x];
11        else {
12          $even $even "," $numbers[$x];
13        }
14      else {
15        if($odd == "") {
16          $odd $numbers[$x];
17        else {
18          $odd $odd "," $numbers[$x];
19        }
20      }
21    }
22  }
23?>
24 
25 
26<html>
27<head>
28<title>Odd Even Numbers</title>
29</head>
30<body>
31<h2>Check Odd Even Numbers</h2>
32<form name="myform" action="" method="post">
33<input type="text" name="number" />
34<input type="submit" name="check" value="Check"/>
35 
36<font size="2" color="#FF3333;">sample input: 23,22,43,55,12,32,11</font>
37 
38</form>
39<?php if($odd != "" || $even != "") {?>
40  <h3>Odd Numbers</h3>
41  <?php echo $odd; ?>
42 
43  <h3>Even Numbers</h3>
44  <?php echo $even; ?>
45 
46<?php } ?>
47</body>
48</html>




HOW IT WORKS


The following statement will check if our textfield exist using isset() function and if contains value:
1if(isset($_POST['check']) && trim($_POST['check']) != "") {
isset() - Determine if a variable is set and is not NULL.
trim() - Strip whitespace (or other characters) from the beginning and end of a string.

Then convert the value to an array so that it will be easy for us to access the value one-by-one.
1$numbers explode(",", trim($_POST['number']));
explode() - Split a string by string and returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.

This statement will determine if the number is array using modulo by 2. We use 2 so that we have remainder of either 0 or 1, 0 if even and 1 if odd number.
1if (($numbers[$x]%2) == 0) {
modulo operation - finds the remainder of division of one number by another.

Display all the result if contains value.
1<?php if($odd != "" || $even != "") {?>
2  <h3>Odd Numbers</h3>
3  <?php echo $odd; ?>
4 
5  <h3>Even Numbers</h3>
6  <?php echo $even; ?>
7 
8<?php } ?>

0 comments:

Post a Comment

Internet-PublicLab. Powered by Blogger.