What's new

PHP HELP. Warning: Undefined array key "numbers" when Reset button is clicked

0greanne

Grasshopper
Joined
Dec 11, 2021
Posts
2
Reaction
0
Points
12
this is the ses1.php
<?php
session_start();
?>
<html>
<body>
<?php
echo "<p><font size='5'>Input whole numbers from 1 to 100 only</p>";
?>

<form action="" method="post">
Input numbers: <input type="number" name="num" min="1"
max="100" required>
<!-- submit button -->
<input type="submit" value="Submit">
</form>
<!-- reset button -->
<form action="ses2.php" method="post">
<a href="location:ses2.php"><input type="submit" value="Reset"></a>
</form>

<?php
if(!empty($_POST['num']))
{error_reporting( error_reporting() & ~E_NOTICE );
$num=$_POST['num'];
$_POST['num'] = $_SESSION['numbers']?:[];
$_SESSION['numbers'] = $_SESSION['numbers']?:[] ;
if (in_array($num, $_SESSION['numbers']))
{error_reporting( error_reporting() & ~E_NOTICE );
echo '<script>alert("already exists!")</script>';
}
else
{
$_SESSION['numbers'][]=$num;
}

sort($_SESSION['numbers']);
echo "Number: ";
echo implode(" ",$_SESSION['numbers']);
}
?>
</body>
</html>


and this is the ses2.php file

<?php
session_start();
session_destroy();
unset($_SESSION['numbers']);
header('Location: ses1.php');
exit();
?>


the reset button do its job to reset the session but after submitting new input for the new session. this is the message that occurs whenever i click the reset button.

Warning: Undefined array key "numbers" in C:\xampp\htdocs\probset\ses1.php on line 25
Warning
: Undefined array key "numbers" in C:\xampp\htdocs\probset\ses1.php on line 26
 
Wrong implementation of ternary operator:

Ternary operator ?: is a shorthand for if else:
PHP:
// (condition) ? (return if true) : (return if false)
Use ?? null coalescing instead
PHP:
// (if true return this) ?? (if false return this)

$_POST['num'] = $_SESSION['numbers'] ?? [];
 
Wrong implementation of ternary operator:

Ternary operator ?: is a shorthand for if else:
PHP:
// (condition) ? (return if true) : (return if false)
Use ?? null coalescing instead
PHP:
// (if true return this) ?? (if false return this)

$_POST['num'] = $_SESSION['numbers'] ?? [];
thank you for replying. i found the error at the same day i posted this.
 

Similar threads

Back
Top