Jump to content

need help with $_SESSION


computernerd21

Recommended Posts

using $_SESSION and rand(1,10) function i want to creat this:
odd: random odd number appears
even:random even number appears
sum; sum of all the numbers that have appeared
for ex:
the first two random numbers are
odd:3
even:6
sum:9
and the next number that appears is 5 then it should be like this:
odd:5
even:6
sum:14 meaning(3+6+5)
i tried like this:

 

<?php 
session_start();
$_SESSION["number"] = rand(1,10);
if(isset($_POST["check"])){
if ($_SESSION["number"]%2==0){$_SESSION["odd"]= $_SESSION["number"];
}
else if($_SESSION["number"]%2!=0){$_SESSION["even"]= $_SESSION["number"];
}
else session_register_shutdown();
$_SESSION["sum"] == $_SESSION["odd"]+$_SESSION["even"];
}
 
 
?>
<body>
 
 
<form action="index4.php?check" method="post"> 
ODD number:<?php echo $_SESSION["odd"];?> <br />
EVEN number:<?php echo $_SESSION["even"];?><br />
SUM of all the numbers that have appeared:<?php echo $_SESSION["sum"];?><br />
 
 
 
<input type="submit" value="submit" />
 
 
</form>
</body>
 
but the problem im having is that it cant identify the indexes odd even and sum so if anybody could help me i will aprecciate it :D 

 

 

 

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/284490-need-help-with-_session/
Share on other sites

make $_SESSION["odd"] and $_SESSION["even"] arrays.

 

You can then use array_sum to add up the odd/even numbers together. To list the numbers you can use implode

<?php
// reset session
if(isset($_POST['reset']))
{
    session_destroy();
    unset($_SESSION);
}

session_start();
$_SESSION["number"] = rand(1,10);

// set odd and even sessions to array
if(!isset($_SESSION["odd"]) || !isset($_SESSION["even"]))
{
    $_SESSION["odd"]  = array();
    $_SESSION["even"] = array();
}

if(isset($_GET["check"]))
{
    if ($_SESSION["number"] %2 == 0)
    {
        $_SESSION["even"][] = $_SESSION["number"]; // even number to array
    }
    else
    {
        $_SESSION["odd"][] = $_SESSION["number"]; // odd number to array
    }
} 
 
$_SESSION["sum"] = array_sum($_SESSION["odd"]) + array_sum($_SESSION["even"]); // add up the odd and even number array's

?>
<body>

<form action="" method="post">
    ODD number:  <?php echo implode(',', $_SESSION["odd"]);   /* list odd numbers */ ?> <br />
    EVEN number: <?php echo implode(',', $_SESSION["even"]);  /* list even numbers */ ?><br />
    SUM of all the numbers that have appeared:<?php echo $_SESSION["sum"];?><br />
    
    <input type="submit" name="check" value="submit" />
    <input type="reset" name="reset" value="Reset" />
</form>
</body>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.