How to set up multiple conditions by using switch? - php

I want to code a counting game on php.
The rule is like the following:
1. Player selects a number from 0~3
2. Computer selects a number from player's selection + 0~3
3. The one arrive 30 lose the game
The code I have written :
<?php
$total = $_POST['total'];
$user_number = $_POST['number']; // 1~3
$total='';
switch ($total){
case '4':
case '8':
case '12':
case '16':
case '20':
case '24':
case '28':
$computer_selection = 1;
break;
case '3':
case '7':
case '12':
case '16':
case '20':
case '23':
case '27':
$computer_selection = 2;
break;
case '2':
case '6':
case '11':
case '15':
case '19':
case '22':
case '26':
$computer_selection = 3;
break;
default:
$computer_selection =1;
break;
}
$computer_number = $total + $computer_selection;
$total = $user_number + $computer_number;
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>恐怖の30ゲーム</title>
</head>
<body>
<?php print_r('The choice of computer'.$computer_number.'<br>'); ?>
<?php print_r('Current number:'.$total.'<br>'); ?>
恐怖の30
<?php
$total_nubmer1=$total+1;
$total_number2=$total+2;
$total_number3=$total+3;
?>
<form method='post' action='index2.php'>
you:
<select name='number'></br>
<option value='<?php echo $total_nubmer1 ?>'><?php echo
$total_nubmer1 ?></option>
<option value='<?php echo $total_number2 ?>'><?php echo
$total_number2 ?></option>
<option value='<?php echo $total_number3 ?>'><?php echo
$total_number3 ?></option>
</select>
<input type='hidden' name='total' value='<?php $total?>'>
<input type='submit' value='登録'>
</form>
</body>
</html>
<?php
if ($user_number>=30){
echo "<script language=\"JavaScript\">alert(\"you lose\");location.href='index.php';</script>";
}else if($user_number<=29 && $user_number>28||$total>29){
echo "<script language=\"JavaScript\">alert(\"you win\");location.href='index.php'</script>";
}
?>
I dont't understand why the output at computer_selection always goes to default.

Because you put this : $total=''; just before the switch.
So, the $total always enter in the default case of your switch.

You are reassigning the value of $total before entering to the switch. Another thing that you are doing is assuming that the value of $total is recieved in the $_POST param, you shoul check if the value is set first. So remove the $total = ''; line and do something like this in your assignment
$total = (isset($_POST['total']))?$_POST['total']:'';
Same goes for number. That way if nothing is recieved it will go default.
Hope it helps!

Related

Validation for a Divide by Zero in PHP

I'm making a simple Calculator in PHP and want to create validation for a divide by 0.
At the moment when a user divides by zero, PHP issues the warning Warning: Division by zero in
I know I need to check if y == 0 if the user is doing division, but I'm unsure where to put it in my code.
<html>
<head>
<title>PHP Calculator</title>
</head>
<body>
<h3>PHP Calculator (Version 6)</h3>
<p>Add, subtract, divide or multiply and output the result</p>
<form method="get" action="<?php print $_SERVER['PHP_SELF']; ?>">
<input type = "number" name = "x" placeholder = "0" required>
<select name = "operator">
<option>None</option>
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type = "number" name = "y" placeholder = "0" required>
<input type="submit" name="submit" value="Calculate"/>
</form>
<p>The answer is: </p>
<?php
if (isset($_GET['submit'])) {
$x = $_GET['x'];
$y = $_GET['y'];
$operator = $_GET['operator'];
switch ($operator) {
case "+":
echo $x + $y;
break;
case "-":
echo $x - $y;
break;
case "*":
echo $x * $y;
break;
case "/":
echo $x / $y;
break;
default:
echo "You should to select a method!";
break;
}
}
?>
</body>
</html>
I would put it in the switch statement in division case,
case "/":
echo $y==0 ? 'Illegal divisor' : ($x / $y);
break;
This will ensure readability of your code.
If you're not familiar with the ternary operator here's the syntax:
{condtion} ? {true statement} : {false statement}

A non numeric value encountered in ..... on line 35

This is the code that I'm using. All the arithemetic operations are done successfully except subtraction. When Subtraction is selected, it gives the error. If I use two different echo statements, one for "The answer is: " and the other echo statement for the subtraction between two variables, it gives no error. What is the reason behind the generation of this error when both the variables string are printed using one echo statement??
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Calculator</title>
</head>
<body>
<form>
<input type="text" name="num1" placeholder="First Number">
<input type="text" name="num2" placeholder="Second Number">
<select name="operator">
<option>None</option>
<option>Add</option>
<option>Subtract</option>
<option>Multiply</option>
<option>Divide</option>
</select>
<br>
<button name="submit" value="submit">Calculate</button>
</form>
<?php
if (isset($_GET['submit'])) {
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
$operator = $_GET['operator'];
switch ($operator) {
case "None":
echo "You need to set a method!";
break;
case 'Add':
echo "The answer is: ".$num1 + $num2;
break;
case 'Subtract':
echo "The answer is: ".$num1 - $num2;
break;
case 'Multiply':
echo "The answer is: ".$num1 * $num2;
break;
case 'Divide':
echo "The answer is: ".$num1 / $num2;
break;
}
}
?>
</body>
</html>
https://www.php.net/manual/en/language.operators.precedence.php
The . in your string concatenation has a higher operator precedence than your -. You should add parentheses around your $num expressions.
switch ($operator) {
case "None":
echo "You need to set a method!";
break;
case 'Add':
echo "The answer is: ".($num1 + $num2);
break;
case 'Subtract':
echo "The answer is: ". ($num1 - $num2);
break;
case 'Multiply':
echo "The answer is: ".($num1 * $num2);
break;
case 'Divide':
echo "The answer is: ".($num1 / $num2);
break;
}

Keep value selected in the drop down even after form has been submitted iin php

<?php
?>
/* Array to store days in a week*/
$NoofDays=array("Monday","Tuesday","Wednesday","Thurseday","Friday","Saturday","Sunday");
?>
<div class="form-wrapper">
<form action="" method="post">
<select name="days">
<?php foreach($NoofDays as $days){?>
<option <?php if( $daysTitle== '$days')?> selected="selected"> <?php echo $days;?></option>
<?php } ?>
</select>
<button type='submit' class="btn">Submit me</button>
</form>`enter code here`
</div>
<?php
/* Script to generate the Switch case */
if (isset($_POST['days'])) {
$selected = $_POST['days'];
switch ( $selected) {
case "Monday":
echo "Laugh on Monday, Laugh for danger";
break;
case "Tuesday":
echo "Laugh on Tuesday, Laugh for stranger";
break;
case "Wednesday":
echo "Laugh on Wednesday,Laugh for Letter";
break;
case "Thurseday":
echo " Laugh on Thurseday,Something better";
break;
case "Friday":
echo "Laugh on Friday,Laugh for sorrow";
break;
case "Saturday":
echo "Laugh on Saturday,Joy Tommorow!";
break;
default:
echo "Laugh on Every day for some reason:)";
}
}
?>
Thanks anyone for answering the question. Format the code will make it easier to visible the errors. This is PHP code (PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language)
<option <?php if (isset($_POST['days']) && $_POST['days'] === $days): ?>selected="selected"<?php endif; ?>><?php echo $days; ?></option>
<select name="days">
<?php
foreach($NoofDays as $day)
{
$selected = (!empty($_POST['days']) && $_POST['days'] == $day) ? ' selected="selected"' : '';
echo sprintf('<option value="%s"%s>%s</option>', $day, $selected, $day);
}
?>
</select>
even better: use any third party template engine - PHP alone is an ugly one.

Calculator selection stays after submit

Hello i'm trying to make a calculator.And i have this problem : I'm tryng to make the selection that i made it to stay after submit. I've found some code on google for my selection to stay after submit but my calculator won't work anymore. Can you help me ?
here is the code when my calculator works but my selection doesn"t stays after submit
<html>
<body>
<center>
<form method="post">
Food:
<Select name="Dropdown"><br>
<option>Cheese</option>
<option>Apple</option>
<option>Egg</option>
</select>
</br>
Amount:
<input name="amount" type="text">grams<br><br>
<br><input type="Submit" value="Calculate">
<br><br>
<?php
$result=$_POST['result'];
$Dropdown=$_POST['Dropdown'];
$amount = $_POST['amount'];
switch ($Dropdown){
case 'Cheese':
$result= (7.74 * $amount) / 100;
echo "<p> $result </p>";
break;
case 'Apple':
$result= (1.94 * $amount) / 100;
echo "<p> $result </p>";
break;
case 'Egg':
$result= (13.74 * $amount) / 100;
echo "<p> $result </p>";
}
?>
</form>
</center>
</body>
</html>
and here is my code when my slection stays after submit but my calculator won't work
<html>
<head></head>
<body>
<center>
<?php
if (!empty($_POST['Dropdown'])) {
$dropDownVal = $_POST['Dropdown'];
} else {
$dropDownVal = 1;
}
?>
<form method="post">
<select name="Dropdown" >
<option value="1" <?php if ($dropDownVal==1) echo 'selected="selected"'; ?>>Cheese </option>
<option value="2" <?php if ($dropDownVal==2) echo 'selected="selected"'; ?>>Apple</option>
<option value="3" <?php if ($dropDownVal==3) echo 'selected="selected"'; ?>>Egg</option>
</select>
<?php
$result=$_POST['result'];
$Dropdown=$_POST['Dropdown'];
$amount = $_POST['amount'];
switch ($Dropdown){
case 'Cheese':
$result= (7.74 * $amount) / 100;
echo "<p> $result </p>";
break;
case 'Apple':
$result= (1.94 * $amount) / 100;
echo "<p> $result </p>";
break;
case 'Egg':
$result= (13.74 * $amount) / 100;
echo "<p> $result </p>";
}
?>
<input name="amount" type="text">grams<br><br>
<br><input type="Submit" value="Calculate">
</form>
</center>
</body>
</html>
Thanks
What you receive back in the $_POST['Dropdown'] is the value not the content so you will get 1 or 2 or 3 and not the Cheese or Apple or Egg.
So try:
switch ($Dropdown){
case 1: // Cheese
$result= (7.74 * $amount) / 100;
break;
case 2: //Apple
$result= (1.94 * $amount) / 100;
break;
case 3: // Egg
$result= (13.74 * $amount) / 100;
break;
default:
$result = 0;
}
echo "<p> $result </p>";
?>
In future if you are not sure what is in a variable that is returned from the user do a
echo '<pre>' . print_r( $_POST, TRUE ) . '</pre>';
to get a nice display of the array on the browser.
Or a
var_dump( $var );

How to select an option in a dropdown list based on a selection in another dropdown list

I have two DropDown lists which are already populated from the database. If you select a value in DropDownlist1 - Dropdownlist2 gets the same value that was selected in Dropdownlist1.
But the code is based on switch case and also the options are hard coded ! In future - Many options might spring up and it will not work !
So what I want is If you select an option in Dropdown list 1 - The option should be selected in DropDown list 2 based on the "value" and not "index" Like here
Any pointers or help would be appreciated ! Thanks in advance
function showSelected(f) {
var selNum = f.type1.selectedIndex;
//var selText = f.type1.options[selNum].text
switch (selNum)
{
case 1:
document.getElementById('type2').selectedIndex= 2;
break;
case 2:
document.getElementById('type2').selectedIndex = 8;
break;
case 3:
document.getElementById('type2').selectedIndex = 3;
break;
case 4:
document.getElementById('type2').selectedIndex = 1;
break;
case 5:
document.getElementById('type2').selectedIndex = 4;
break;
case 6:
document.getElementById('type2').selectedIndex = 2;
break;
case 7:
document.getElementById('type2').selectedIndex = 2;
break;
case 8:
document.getElementById('type2').selectedIndex = 7;
break;
}
}
<select name="Type1" id="Type1" onchange="showSelected(this.form)" >
<option>Select Option</option>
<option value="<?php echo $record->getID();?>" > <?php echo $record->getIDName();?> </option>
</select>
<select name="Type2" id="Type2" disabled>
<option>Select Option</option>
<option value="<?php echo $record->getID();?>" ><?php echo $record->getIDValue();?> </option>
</select>
function selectoption()
{
var list = document.getElementById('list');
var listtwo = document.getElementById('listtwo');
var searchtext = list.options[list.selectedIndex].text;
for(var i = 0; i < listtwo.options.length; ++i)
if (listtwo.options[i].text === searchtext) listtwo.options[i].selected = true;
}
http://jsbin.com/oyaloc/2
When you're printing out all of the options in the select boxes, you can give the options ids related to their index in the array:
<select id='first_combo_box' onchange='selected(this);'>
<?php
foreach( $arrayOfOptions as $index => $option ):
?>
<option value='<?php echo $option?>' id='first_combo_index_<?php echo $index?>'><?php echo $option ?></option>
<?php
endforeach;
?>
</select>
<select id='second_combo_box' onchange='selected(this);'>
<?php
foreach( $arrayOfOptions as $index => $option ):
?>
<option value='<?php echo $option?>' id='second_combo_index_<?php echo $index?>'><?php echo $option ?></option>
<?php
endforeach;
?>
</select>
And then in your javascript:
function selected(selectElt) {
var index = selectElt.selectedIndex;
document.getElementById('first_combo_index_' + index).selected = true;
document.getElementById('second_combo_index_' + index).selected = true;
}
It'd be pretty easy to parse which 'select' element you're sending to the function, so that you only change the selected option of the OTHER select element, but it's late and I'm tired so I'll leave that to you :)

Categories