Mark Luiken
Mark Luiken

Reputation: 19

Add +1 number to an array

session_start();

echo "<form method='post'>";
echo "<input type='text' name='random' placeholder='Product' >";
echo "<input type='submit' value='submit' name='submit'>";
echo "</form>";

if(!$_SESSION['list']) {
    $_SESSION['list'] = array(); // create session
}
if(isset($_POST['submit']) && empty($_POST['random'])) { // Check if input is empty
    echo "* Input is empty!";
} elseif(isset($_POST['submit']) && isset($_POST['random'])) {
    $_SESSION['list'][] += 1; // add +1 to array
}

foreach ($_SESSION['list'] as $value) {
    echo $value . "<br>"; // shows the list/array
}

So I tried to make array that add +1 number on a submit, but my array keeps being 1, so it doesn't go like: 1,2,3,4,5... but it goes like: 1,1,1,1,1,1 . They don't add up. How do I fix this?

Upvotes: 0

Views: 155

Answers (1)

Just a student
Just a student

Reputation: 11050

Given an array $arr, or $_SESSION['list'] in your case, it is possible to append an element to the end of the array as follows.

$arr[] = 'new element';

You try to combine this with the += operator. This will first append 0 to the array and then increment it, resulting in 1 being appended all the time.

It looks like what you actually want to do is this:

$arr[] = end($arr) + 1;

That is, take the last value of the array, add 1 to it and append that to the array.

Upvotes: 1

Related Questions