0

How do I increment an array value with session

<?php
session_start();

$my_array=array(5,9,3);
$_SESSION['animals']=$my_array;
$_SESSION['animals'][0]= $_SESSION['animals'][0]+1;
echo "animals=". $_SESSION['animals'] [0];

$_SESSION['views']=$_SESSION['views']+1;
echo "Views=". $_SESSION['views'];

echo "<form method='post' action='realsession.php'>
 <input type='submit'>
  </form>";
?>

Views works fine, every time I hit submit it adds 1. However animals gives me 6 regardless of hitting submit. So how do I increment the array value?

thanks

4 Answers 4

4

Try with:

session_start();

if ( !isset($_SESSION['animals']) ) {
  $_SESSION['animals'] = array(5,9,3);
}
$_SESSION['animals'][0]++;
Sign up to request clarification or add additional context in comments.

1 Comment

If you find my answer helpful, remember to mark it with tick on the left.
0

Every time the script runs, you're setting $_SESSION["animals"][0] is being set to 5:

$myarray = array(5,9,3);

And you're setting that to animals. Check if it's set by using isset();

Comments

0

You are resetting the array value for animals every time the script runs and then incrementing the value that you just set. Remove the following lines:

$my_array=array(5,9,3);
$_SESSION['animals']=$my_array;

Comments

0

With this bellow

$my_array=array(5,9,3);

You give initial values.

You need to check if $_SESSION has stored array already. so below that line, add

if(isset(SESSION['animals'] && count(SESSION['animals'])!=0){
 $my_array=SESSION['animals'];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.