PHP functions and if/else statements - php

I am trying to write a script that includes if/else statements and functions. some background
$parts first character should have the letter "N"
$desc is suppose to be at least one character long
$price needs to be positive (0 or higher)
if all three of theses requirements are met then it should say "data accepted" if something is not met (one or all) the "Invalid...." needs to show.
can someone tell me what part of my script I should look at.
<?php
$parts = $_POST["parts"];
$desc = $_POST["desc"];
$price = $_POST["price"];
$pa = substr($parts, 0, 1);
$de = strlen($desc);
if ($pa != "N")
{echo "Invalid Part Number";}
else
if ($de <= 1)
{echo "Invalid Description Length";}
else
if ($price <= 0)
{echo "Invalid Price";}
else
{echo "Data Accepted";}
?>

The second if should be if($de==1) $de=1 will always return true.
Also add semicolons after each statement.

Your requirement:-
$parts first character should have the
letter "N"
$desc is suppose to be at least one
character long
$price needs to be positive (0 or
higher)
Solution:-
$parts = $_POST["parts"];
$desc = $_POST["desc"];
$price = $_POST["price"];
$pa = substr($parts, 0, 1);
$de = strlen($desc);
if($pa != 'N') {
echo "Invalid Part Number";
} elseif($de < 1) {
echo "Invalid Description Length";
} elseif($price < 0) {
echo "Invalid Price";
} else {
echo "Data Accepted";
}

the second if should be if($de < 1) you can have if($de == 1) if its always going to be one character long but this will work if its 1 or more

$parts = $_POST["parts"];
$desc = $_POST["desc"];
$price = $_POST["price"];

<?php
$parts = '';
$desc = '';
$price = 0;
if ($_POST['parts'] != 'n')
{
echo 'Not equal to n<br>';
}
else {
'Accepted input<br>';
}
$desc = strlen($_POST['desc']);
if ($desc < 1)
{
echo 'Input less than 1<br>';
}
else {
echo 'Accepted input<br>';
}
if ($_POST['price'] < 0)
{
echo 'Input below 0<br>';
}
else {
echo 'Input accepted<br>';
}
?>

Related

Assistance required with basic Rock, Paper, Scissors game

I'm new to php and have been struggling to get my rock, paper, scissors game to work! I know what I'm trying to do but just can't get my head aound where I've gone wrong......it works for rock but for paper and scissors I'm getting two outputs!!Please help a novice out...thanks!!
P.S I know there are much slicker ways of doing this!!
<?php
// user enters a value R P or S - NEED TO RETURN A COUPLE OF
TIMES AFTER, not sure why?
echo "What do you select - R for rock, P for paper or S for
scissors?\n";
$input=
$R = stream_get_line(STDIN, 1, "\n");
$P = stream_get_line(STDIN, 1, "\n");
$S = stream_get_line(STDIN, 1, "\n");
//program converts the value into Rock, Paper or Scissors
switch ($input) {
case 'R' :
case 'r':
echo $R = "You selected Rock\n" ;
break;
case 'P' :
case 'p':
echo $P = "You selected Paper\n" ;
break;
case 'S' :
case 's':
echo $S = "You selected Scissors\n" ;
break;
}
//computer generates a random value 0,1,2 & converts to R P or S
echo "\nComputer is now making its selection....\n";
//$options = ('Rock=0, Paper=1, Scissors=2');
$output = (rand(0,2) );
echo $output;
if ($output== 0)
{
echo "\nComputer Selected Rock\n"; //goto Rock;
}
elseif ($output==1)
{
echo "\nComputer Selected Paper\n"; //goto Paper;
}
elseif ($output==2)
{
echo "\nComputer Selected Scissors\n"; //goto Scissors;
}
//compare user and computers choise
Rock:
if ($R && $output===0)//.($P && $output==1),($S && $output==2))
{
echo "\nITS A DRAW";
}
elseif ($R && $output===1)//.($P && $output==2).($S &&
$output==0))
{
echo "\nCOMPUTER WINS";
}
elseif ($R && $output===2)//.($P && $output==0).($S &&
$output==1))
{
echo "\nYOU WIN";
}
Paper:
if ($P && $output===1)
{
echo "\nITS A DRAW";
}
elseif ($P && $output===2)
{
echo "\nCOMPUTER WINS";
}
elseif ($P && $output===0)
{
echo "\nYOU WIN";
}
Scissors:
if ($S && $output===2)
{
echo "\nITS A DRAW";
}
elseif ($S && $output===0)
{
echo "\nCOMPUTER WINS";
}
elseif ($S && $output===1)
{
echo "\nYOU WIN";
}
You should inicialize $R, $P and $S to false first. Then read user input 1x into $input.
The rest of the script seams to be ok.
<?php
$R = $P = $S = false;
$input= stream_get_line(STDIN, 1, "\n");
// user enters a value R P or S - NEED TO RETURN A COUPLE OF TIMES AFTER, not sure why?
because
$input=
$R = stream_get_line(STDIN, 1, "\n");
$P = stream_get_line(STDIN, 1, "\n");
$S = stream_get_line(STDIN, 1, "\n");
You're calling stream_get_line() three times so your script wants three lines of input.
Also, I'm not sure if this was intended, but you're getting your user input seemingly purely by chance as $input = $R = stream_get_line() stores the first user input in $R and $input.
I'd suggest only doing $input = stream_get_line() and nothign else.
Then in your switch/case block you do e.g. echo $R = "..."; and further down you do if ($R && ...).
Evaluating strings as booleans is not recommended.
I would recommend something like
$R = $P = $S = false; // initialize all variables to false
switch ($input)
{
case "R":
$R = true; // set selected variable to true
echo "You have selected Rock\n";
break;
// ...
}
Finally, you seem to be using jump marks to comment your code.
Rock:
if ( ...
While this doesn't cause any problems (yet), it's generally considered bad style to abuse language features for documentation purposes.
These should become comments:
// Rock
if ( ...

Why doesn't subtraction sign work on while loop in php?

<?php
$hp = 0;
while($hp < 50) {
$flip = rand(0,2);
if ($flip == 1) {
echo "<p>X-Ray</p>";
$hp += 15;
} elseif ($flip == 2) {
echo "<p>Special Move</p>";
$hp += 10;
} else {
echo "<p>Punch</p>";
$hp += 5;
}
echo "<p>Total so far: $hp</p>";
echo "</br>";
}
?>
This is a PHP code. When I run it, it works fine. However, when I change it to this code below it doesn't.
<?php
$hp = 50;
while($hp > 1) {
$flip = rand(0,2);
if ($flip == 1) {
echo "<p>X-Ray</p>";
$hp -= 15;
} elseif ($flip == 2) {
echo "<p>Special Move</p>";
$hp -= 10;
} else {
echo "<p>Punch</p>";
$hp -= 5;
}
echo "<p>Total so far: $hp</p>";
echo "</br>";
}
?>
Please help. tHE CHANGES I MADE ARE THE HIGHLIGHTED ONES.
You never created $hp properly in the second version:
50;
doesn't do anything. It just tells php "here, have a 50", and php goes "gee, thanks, ok, whatever" and moves onwards. Then you have
while($hp > 1) {
Since $hp is undefined, it's null, and the code parses/executes as:
while($hp > 1) {
while(null > 1) {
while(0 > 1) {
FALSE -> exit loop
You never created $hp properly in the second version:
50;
If you do change it to $hp = 50;

deleting white space at the end of for loop output in php

can any body help me how I can delete the white space at the end of the output.
This might be easy question but to be honest it took me more than 45 minutes and still nothing. Assignment
Write a PHP script that prints the numbers from the number inputted on form to zero. The numbers should be separated with a single space but the last number, zero, should not have a space after it. If the user inputs a number smaller than zero, print “The number should be at least zero!” The used form looks like this:
Luku:
Example output
5 4 3 2 1 0
my code:
<?php
$number=$_GET["number"];
if ($number < 0){
echo "The number should be at least zero!";
} else {
for($i=$number; $i>=0; $i=$i-1)
{
echo $i." ";
}
}
?>
You can use trim()
<?php
$number=$_GET["number"];
if ($number < 0){
echo "The number should be at least zero!";
} else {
$num = '';
for($i=$number; $i>=0; $i=$i-1)
{
$num .= $i." ";
}
echo trim($num);
}
?>
Try this:
echo implode(" ",range($number,0));
Magic and trickery ;)
You can use rtrim instead of trim to delete white spaces at the end of the string:
<?php
$number=$_GET["number"];
if ($number < 0){
echo "The number should be at least zero!";
} else {
for($i=$number; $i>=0; $i=$i-1)
{
$num .= $i." ";
}
}
$num = rtrim($num);
?>
You could use an if-statement:
<?php
$number=$_GET["number"];
if ($number < 0) {
echo "The number should be at least zero!";
} else {
for($i=$number; $i>=0; $i=$i-1)
{
echo $i . ($i != 0 ? " " : "");
}
}
Or you use trim:
<?php
$number=$_GET["number"];
$output = "";
if ($number < 0) {
echo "The number should be at least zero!";
} else {
for($i=$number; $i>=0; $i=$i-1)
{
$output .= $i . " ";
}
}
echo trim($output);
try this:
<?php
$number=$_GET["number"];
if ($number < 0) {
echo "The number should be at least zero!";
} else {
$string = $number;
for($i=$number-1; $i>=0; $i=$i-1)
{
$string .= " $i";
}
}
echo $string;
?>

Is there any way something like this possible?

<?php
$division=$row['mark'];
$pass="Passed";
if($division>=80 && $pass==include "result.php")// Result.php has two value: one is `Pass` and the other is `Fail`.
{
echo "Letter";
}
elseif($division>=70 && $pass==include "result.php")
{
echo "First";
}
else
{
echo "Fail";
}
?>
What I want to output here is: if $division is equal to 80 and at the same time if $pass is equal to Passed, echo Letter. But if $division is less than 70, echo Fail; also $pass here equals to fail which is taken from result.php. I have been trying to output it with following code, but it does not work. It outputs FailFailFailFail when $division is less than 70.
Code for Result.php
<?php
$eng=40;
$mizo=40;
$hindi=40;
$maths=40;
$ss=40;
$science=40;
if ($eng>=40 && $mizo>=40 && $hindi>=40 && $maths>=40 && $ss>=40 && $science>=40)
{
echo "<font color=green>Passed</font>";
}
else
{
echo "<font color=red>Failed</font>";
}
?>
You are going about this all the wrong way. You can't compare the results of an include like that, not to mention they don't match properly anyway as you're comparing a single word string against a string with a whole bunch of HTML in it.
A better way to do it is to include results.php and store your answer in a variable. I have written an example below.
First off you need to change result.php to:
<?php
$eng=40;
$mizo=40;
$hindi=40;
$maths=40;
$ss=40;
$science=40;
if ($eng>=40 && $mizo>=40 && $hindi>=40 && $maths>=40 && $ss>=40 && $science>=40)
{
$test = "Passed";
}
else
{
$test = "Failed";
}
?>
Then you put the following in the first file:
<?php
$division=$row['mark'];
$pass="Passed";
include("result.php");// Result.php has two value: one is `Pass` and the other is `Fail`, store in $test.
if($division>=80 && $pass==$test)
{
echo "Letter";
}
elseif($division>=70 && $pass==$test)
{
echo "First";
}
else
{
echo "Fail";
}
?>
Something like this will do. For your result.php, use the following:
<?php
$eng= 40;
$mizo= 40;
$hindi= 40;
$maths= 40;
$ss= 40;
$science= 40;
// first group your variable into one array = $all
$all = array($eng, $mizo, $hindi, $maths, $ss, $science);
// second, just iterate over them till you find one value -40
for($i=0; $i < count($all); $i++){
if($all[$i] < 40) $sum = 1;
}
?>
For output:
<?php include "result.php";?>
<?php
$division=$row_['mark'];
$pass="Passed";
$test = (!empty($sum)) ? 'Failed' : 'Passed';
if($division>=80 && $pass==$test)
{
echo "Letter";
}
elseif($division>=70 && $pass==$test)
{
echo "First";
}
else
{
echo "Passed";
}
?>
You need to include the file first:
<?php
include "result.php"; //include the file
$division =$ row['mark'];
$pass = "Passed";
if($division == 80 && $pass == "Passed") {
echo "Letter";
}
elseif($division < 70) {
echo "Fail";
}
?>

PHP code how to clean user input from $_POST

I have this PHP code:
<?php
$score11 = $_POST['passmarks12'];
if($_POST['passmarks12'] > 100){
$grade11 = "";
}
elseif ($_POST['passmarks12'] < 45){
$grade11 = "Fail";
}
$strg = " $grade11";
echo $strg;
?>
The code is always printing "Fail" regardless of what is sent in.
I want it so that if it passes in blank or invalid input it fails.
And how should I properly cleanse the input?
Try this:
<?php
//$_POST['passmarks12'] = '';
if(empty($_POST['passmarks12']) || $_POST['passmarks12'] > 100)
{
$grade11 = "";
}
else if ($_POST['passmarks12'] < 45){
$grade11 = "Fail";
} else{
$grade11 = "Pass";
}
$strg = " $grade11" ;
echo $strg;
?>
Points:
Check if $_POST['key'] exists using isset.
Check if $_POST['key'] has a valid data type, string.
It may come as array.
Check if $_POST['key'] has a valid numeric format.
Compare $_POST['key'](String) and 45(Integer), using intval.
Example:
<?php
switch (true) {
case !isset($_POST['passmarks12']):
case !is_string($score = $_POST['passmarks12']):
case !is_numeric($score):
$result = 'Error (Invalid parameter)';
break;
case (intval($score) < 45):
$result = 'Fail (Less than 45)';
break;
default:
$result = 'Success (No less than 45)';
}
echo $result;
I think you want
elseif ($_POST['passmarks12'] < 45 && !empty($_POST['passmarks12']))
This PHP code will make sure $_POST is not empty before comparing it to 100.
<?php
$score11 = $_POST['passmarks12'];
if(empty($_POST['passmarks12']) || $_POST['passmarks12'] > 100)
$grade11 = "";
elseif ($_POST['passmarks12'] < 45)
$grade11 = "Fail";
$strg = " $grade11" ;
echo $strg;
?>

Categories