How to add more values to array on button click in PHP

Viewed 415

I'm trying to add values to array on button click.

Here is my code:

<?php

$user_hand = [];
$dealer_hand = [];

$rand = mt_rand(0, 15);

if(isset($_POST['posh'])){
    array_push($user_hand, $rand);
}

print_r($user_hand);

?>

<form method="post"><input type="submit" name="posh"></form>

What I am achieving atm is Array ([0] => 11), while I want to achieve this after 3 times clicking the button: Array ([0] => 11, [1] => 4, [2] => 6)

How can I achieve this?

1 Answers
<?php
// start session to add/update/read session variables
session_start();

// create empty array if key is not present in session
if(!isset($_SESSION['user_hand'])) {
    $_SESSION['user_hand'] = [];
}
if(!isset($_SESSION['dealer_hand'])) {
    $_SESSION['dealer_hand'] = [];
}

$rand = mt_rand(0, 15);

// push value in session variable or array
if(isset($_POST['posh'])){
    array_push($_SESSION['user_hand'], $rand);
}

print_r($_SESSION['user_hand']);
// Optional but recommended to close session for writing as we don't want to update session data anymore
session_write_close(); 
?>

<form method="post"><input type="submit" name="posh"></form>

This should fix your issue.

Related