I am making a number guessing game, where the person guesses different numbers until they guess the correct number, I want to record these different guesses into an array using the same variable but it only records the most recent guess, is there a way so that it records all guesses in this array?
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
$_SESSION['incorrect'] = array();
if(isset($_POST['submit'])){
if(1 <= $_POST['guess'] && $_POST['guess'] <= 100){
$guess = $_POST['guess'];
if($guess < $number){
echo "Your Number is Too Low";
$_SESSION['guesses']++;
array_push($_SESSION['incorrect'], $guess);
} elseif($guess > $number){
echo "Your Number is Too High";
$_SESSION['guesses']++;
array_push($_SESSION['incorrect'], $guess);
} else {
echo "Good Job <br>";
echo $_SESSION['guesses']. "<br>";
print_r($_SESSION['incorrect']);
}
}else {
echo "Please Enter a Number Between 1 and 100";
}
}
I think the problem is you’re setting the incorrect array to an empty array every time the page is loaded.
Fix it by changing the part where you set the incorrect array to:
if (!isset($_SESSION[“incorrect”])){
$_SESSION[“incorrect”] = array();
}
Related
I'm trying to get a n else statement working with a print_r such that if there's no value it outputs "no values".
In the code I'm getting values from json converted to an array.
The logic I'm trying to achieve is
IF fieldTag contains "i" THEN output the content associated with it
ELSE says its empty.
Right now blank is outputted as opposed to "no values".
Thanks
for($b=0; $b<count($res['entries'][$i]['bib']['varFields']); $b++) //loop thru the varFields
{
if($res['entries'][$i]['bib']['varFields'][$b]['fieldTag'] == "i")
{
$subfieldText2 = $res['entries'][$i]['bib']['varFields'][$b]['subfields'][0]['content']."<br>";
if(count($subfieldText2) > 0) {
print_r($subfieldText2);
} else {
echo "no values";
}
}
}
count() is for arrays, not strings, the way to get the length of a string is with strlen(). And if you want to check for an empty string, just compare it with $var == "", you don't need to get the length.
But you're concatenating "<br>" to the value, so the length will never be zero. You could check the length before concatenating.
$subfieldText2 = $res['entries'][$i]['bib']['varFields'][$b]['subfields'][0]['content'];
if($subfieldText2 != "") {
$subfieldText2 .= "<br>";
print_r($subfieldText2);
} else {
echo "no values";
}
And to avoid having to repeat that long expression to access the field, you could use foreach
for($res['entries'][$i]['bib']['varFields'] as $field) {
if ($field['fieldTag'] == "i") {
$subfieldText2 = $field['subfields'][0]['content'];
...
}
}
this worked for me thanks everyone
$subfieldText2="not detected";
echo "ISBN: ";
for($b=0; $b<count($res['entries'][$i]['bib']['varFields']); $b++) //loop thru the varFields
{
if($res['entries'][$i]['bib']['varFields'][$b]['fieldTag'] == "i")
{
$subfieldText2 = $res['entries'][$i]['bib']['varFields'][$b]['subfields'][0]['content'];
echo $subfieldText2.", ";
}
}
echo $subfieldText2;
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
This is the code that I wrote and it's not working. it's suppose to ask the user a odd number and check is it correct.
Code:
$guess = $_POST['guess'];
$submit = $_POST['submit'];
if(isset($submit)){
if ($guess/2 %0){
echo "the number you are guessing is not odd";
}elseif{
($guess<$rand)
echo "Your Guess is Smaller than the secret number";
}elseif{
($guess>$rand)
echo "Your Guess is bigger than the secret number";
}else{
($guess==$rand)
echo "you guessed currectly. now try anouthe number!";}
else
header("Location: index.php");
exit();}
?>
Can you try this?
You placed the '()' in your elseif wrong.
<?php
$rand = rand(1, 99);
$guess = $_POST['guess'];
$submit = $_POST['submit'];
if(isset($submit))
{
if($guess / 2 % 0)
{
echo "the number you are guessing is not odd";
}
elseif($guess < $rand)
{
echo "Your Guess is Smaller than the secret number";
}
elseif($guess > $rand)
{
echo "Your Guess is bigger than the secret number";
}
elseif($guess == $rand)
{
echo "you guessed currectly. now try anouthe number!";
}
}
else
{
header("Location: index.php");
exit();
}
?>
I have not tested this code, so i need your feedback. Edit: You've confirmed this worked.
I'd like to provide you the manual about elseif:
http://php.net/manual/en/control-structures.elseif.php
Please consider easier/cleaner coding. Personally I like to use ':' instead of '{}', it's less code and easier to read when you use HTML mixed with PHP like:
<?php
$rand = rand(1, 99);
$guess = $_POST['guess'];
$submit = $_POST['submit'];
if(isset($submit)):
if($guess / 2 % 0):
echo "the number you are guessing is not odd";
elseif($guess < $rand):
echo "Your Guess is Smaller than the secret number";
elseif($guess > $rand):
echo "Your Guess is bigger than the secret number";
elseif($guess == $rand):
echo "you guessed currectly. now try anouthe number!";
else:
header("Location: index.php");
exit();
endif;
?>
And don't forget to check the $_POST data.
Same goes for array, but thats a side note:
$arr = array(1 => 'hi', 2 => 'hello'); // old
$arr = [1 => 'hi', 2 => 'hello']; // new
That's not the correct syntax for an if-else construct in php.
The elseif part needs to have a condition right after it (before the opening brace), while else doesn't expect a condition at all.
if ($guess/2 %0){
echo "the number you are guessing is not odd";
} elseif ($guess<$rand) {
// ....
} else {
echo "you guessed currectly. now try anouthe number!";
}
Of course, before your else you have to be sure that the if and elseifs match all the "wrong" cases.
I am brand new to PHP and I am not sure if my technique is even good practice, but my code worked until I added the || (!is_numeric($variable)) portions of my if-statements.
I tested to code by inserting letters into the number fields but ensuring that the length of the string was correct. When I do, the code runs the else-statement and echos ".$jname."added.....etc"". The mysqli_query is commented out for testing. I have tried different versions with more or less parenthesis.
Why won't is_numeric() catch my letters? Am I allowed to do multiple ! arguments in an if-statement?
<?Php
header('Refresh: 3; url=../job_table.php');
require 'connect.php';
$jname = mysqli_real_escape_string($db,$_POST['field1']);
$jname_length = 25;
$jwo = mysqli_real_escape_string($db,$_POST['field2']);
$jwo_length = 7;
$jpo = mysqli_real_escape_string($db,$_POST['field3']);
$jpo_length = 4;
$add_job_query = "INSERT INTO jobs (name, wo_no, po_no) VALUES ('$jname','$jwo','$jpo')";
if(($jname || $jwo || $jpo ) == "") {
echo "<center><h1>Please fill all fields!</h1></center>";
} elseif(!(strlen($jname) <= $jname_length)) {
echo "<center><h1>Name must be less than or equal to ".$jname_length." characters!</h1></center>";
} elseif((strlen($jwo) != $jwo_length) || (!is_numeric($jwo))) {
echo "<center><h1>WO number must be a ".$jwo_length." digit number!</h1></center>";
} elseif((strlen($jpo) != $jpo_length) || (!is_numeric($jwo))) {
echo "<center><h1>PO number must be a ".$jpo_length." digit number!</h1></center>";
} else {
//echo mysqli_query($db,$add_job_query);
echo "<center><h1>".$jname." added!</h1><h1>WO number:".$jwo."</h1><h1>PO number:".$jpo."</h1></center>";
}
echo "<center><h1>Please wait.</h1></center>";
?>
Seems to me that you need something like this instead.
if(empty($jname) || empty($jwo) || empty($jpo)){
echo "<center><h1>Please fill all fields!</h1></center>";
}elseif($jname <= $jname_length){
echo "<center><h1>Name must be less than or equal to ".$jname_length." characters!</h1></center>";
}elseif(($jwo != $jwo_length) || (!is_numeric($jwo))){
echo "<center><h1>WO number must be a ".$jwo_length." digit number!</h1></center>";
}elseif(($jpo != $jpo_length) || (!is_numeric($jwo))){
echo "<center><h1>PO number must be a ".$jpo_length." digit number!</h1></center>";
}else{
//echo mysqli_query($db,$add_job_query);
echo "<center><h1>".$jname." added!</h1><h1>WO number:".$jwo."</h1><h1>PO number:".$jpo."</h1></center>";
}
The $count++; does not working while i am using if(!isset($_SESSION["rand"]))...
I am building a number guessing game.
$numOfGess=4;
$min=1;
$max=10;
if(!isset($_SESSION["rand"])){
$_SESSION["rand"] = rand($min, $max);
$count=0;
}
if(isset($_POST["numGuess"])){
$numGuess = $_REQUEST["numGuess"];
if($numGuess != $_SESSION["rand"]) {
//Validation
if($numGuess < $min || $numGuess > $max) {
echo"Your number must be between 1 to 10 !";
}
//Number is Small
if($numGuess < $_SESSION["rand"]) {
echo "too small...";
$count++;
}
//Number is Big
if($numGuess > $_SESSION["rand"]) {
echo "too big...";
$count++;
}
if($count==$numOfGess) {
echo"Game Over!";
unset($_SESSION["rand"]);
}
}
else {
echo"You got it! (in your last chance)";
unset($_SESSION["rand"]);
}
}
You should store the count variable as a session variable as well, otherwise it gets reset with every request. So, just replace $count with $_SESSION['count'] and it should work.
Store count in your session variable. What happens if $_SESSION['rand'] is set? How does it know what the previous count was?
Your forgetting
Session_start()
to start/resume the session
I have loop using for which results in some values:
$value1, $value2, $value3, $value4, ...
How can I make a calculation or relation between these values?
For example, if any two values < 40 echo something?
I hope that some code will make the idea clear:
<?php
$value=$_POST['name'];
for($i=1;$i<=$value;$i++)
{
$value{$i}=$_POST['name{$i}'];
}
if($value{$i} < 40)
{
echo "you failed";
}
else
{
echo "you succeeded";
}
?>
I want to show the message "you failed" if two values are < 40.
How can I do that?
I'm struggling to make sense of what your current code is actually doing, but that could just be that my PHP is a bit rusty. Either way, it sounds like the general pattern of what you're trying to do is to keep a count of fails and successes. As an overall structure (that is, not to be copied/pasted as-is since I don't know what your $value actually is here), it might look something like this:
$fails = 0;
$successes = 0;
for ($i = 0; $i < len($values); $i++)
{
if ($values[$i] < 40)
{
$fails++;
}
else
{
$successes++;
}
}
At this point $fails contains the count of values less than 40 and $successes contains the count of values greater than 40. Then you invoke your business logic for determining the overall result:
if ($fails >= 2)
{
echo "you failed";
}
else
{
echo "you succeeded";
}
To answer your question you can use the foreach statement
$value=$_POST['name'];
$hasValue = 0;
foreach($value as $key => $dat){ // since we have the value from $_POST we use foreach statement to loop it
if($dat < 40){ // check if the data in the list is less than 40
$hasValue++; // increment it if is.
}
}
echo ($hasValue > 2)?#"You failed":#"Success"; // check if it has more than 2 less than 40 values.
something like the above
and try to read about PHP
btw haven't code much in php lately so apologies for some syntax
As soon as any two values add to less than 40, the "failed" message shows and the loops are exited. If not, the success message shows.
$x = false;
foreach ($value as $k1 => $v1) {
foreach ($value as $k2 => $v2) {
if (($v1 + $v2) < 40 && ($k1 != $k2)) {
echo "you failed";
$x = true;
break (2);
}
}
}
if (!$x) echo "you succeeded";