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
Related
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();
}
I'm trying to get a custom function in php to return a random number between 1 and 20 that does not repeat i.e. produce the same number more than once, since I need to subsequently use this number to navigate to one of twenty web pages, and I don't want the same web page displayed.
Here is my code in three steps:
<form action="rand.php">
<p>Click this button to display a random number that does not repeat...</p>
<p><input type="submit" value="Generate"></p>
</form>
Here is rand.php:
require_once('functions.php');
$page = generateNumber();
echo $page;
Here is functions.php:
<?php
$check = array();
function generateNumber() {
global $check;
$page_no = mt_rand(1,20);
$check[] = $page_no;
if (count($check) != 1) {
foreach ($check as $val) {
if ($val == $page_no) {
$page_no = mt_rand(1,10);
continue;
}
}
return $page_no;
}
else {
return $page_no;
}
}
?>
My code seem to be functioning, however, it is repeating numbers so I am obviously doing something wrong. The reason I initially check the count is so that is returns the first number regardless, since it would be a single fresh number.
In order to see the number change I have been refreshing the rand.php page in my browser.
I would keep it simple.
// List numbers 1 to 20
$pages = range(1,20);
// Shuffle numbers
shuffle($pages);
// Get a page
$page = array_shift($pages);
In order to go through all the 20 numbers on each page visit, without repeating, you will need to set a session variable.
<?php
session_start();
if (!isset($_SESSION['numbers'])) {
$_SESSION['numbers']="*"; //---create the session variable
}
function get_number() {
$i = 0;
do {
$num=rand(1,20); //---generate a random number
if (!strstr($_SESSION['numbers'],"*".$num."*")) { //---check if the number has already been used
$_SESSION['numbers']=$_SESSION['numbers'] . $i . "*"; //---add the number to the session variable to avoid repeating
if (substr_count($_SESSION['numbers'],"*")>=21) { //---resets the session variable when all 20 number have been used
$_SESSION['numbers']="*";
}
$i=$num; //---ends the while loop to return the value
}
} while ($i==0);
return $i;
}
?>
I want to have if the variable = null then he makes it to 1.
if the variable exist do nothing and dont make it again to 1.
i got this code:
if (isset($_POST["register"])) {
if(!$l_NextPage){
$l_NextPage = 1;
echo "helaas" . "</br>";
}
if($l_NextPage == 1){
echo "hoi";
$l_NextPage = 2;
}else if($l_NextPage == 2){
echo "doei";
}
}
only the code dont work i tried empty, isset, $var == FALSE but everytime he makes $l_NextPage to 1. is there any solution i tried this too with session but even it don't work!
What am I doing wrong?
what happen when you refresh page, it assign $l_NextPage = 1 every time, thats why all the time hoi printed
you can use sessions for preserving value of variable after page refresh
try this code
// write this line of code at top of php block
session_start();
if (isset($_POST["register"]))
{
if (!isset($_SESSION["l_NextPage"]))
{
$_SESSION["l_NextPage"] = 1;
echo "helaas" . "</br>";
}
if($_SESSION["l_NextPage"] == 1)
{
echo "hoi";
$_SESSION["l_NextPage"] = 2;
}
else if($_SESSION["l_NextPage"] == 2)
{
echo "doei";
//unset( $_SESSION['l_NextPage'] ); unset varibale
}
}
after reaching at prefixed condition you can unset varible using
unset( $_SESSION['l_NextPage'] );
i have not tested code but this should work
you should try:
if(!isset($l_NextPage)) {
$l_NextPage = 1;
echo "helaas" . "</br>";
}
elseif($l_NextPage == 1) {
(...)
try like this,
if(!empty(trim($l_NextPage)))
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";
I just started learning php and I have to do something like this which I got it working but I just have a few questions I want to ask for alternate way of doing but eh first of all the br/ is suppose to be with <> but somehow if i do that the coding at the bottom will see it as a line break.
Anyways if questions are...
With the coding below the outcome will be 0-9 (without 5) but I have to set $zero=-1 if I put $zero=0 then the outcome would be 1-9 (without 5) is there a way I don't have to make $zero=-1 and still have the outcome of 0-9 (without 5)?
I realized I have to put $zero++ before the if and continue statement if I put it at the end of the script after echo "$zero" . "br/"; the script won't run as wanted. Is this how it is suppose to be or I just don't know the other way of doing it.
Thanks in advance for people replying ^_^
$squared = pow(3,2);
echo "\"3 squared is $squared:";
echo "br/";
$zero = -1;
while ($squared > $zero)
{
$zero++;
if ($zero == 5)
{
continue;
}
else if ($squared == $zero)
{
echo "$squared\"";
}
else
{
echo "$zero" . "br/";
}
}
Here it is (you were almost there :P )
$nr = 0;
while ($squared > $nr) {
if (5 == $nr) {
$nr++; // add this
continue;
} else if ($squared == $nr) {
echo "$squared\"";
} else {
echo "$nr" . "<br/>";
}
$nr++; // move to the bottom
}
PS: You're welcome #clement
Change your while loop to while ($squared >= $zero) and then set $zero = 0;
Should work!