PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
<?php
session_start();
$visits = $_SESSION['visits']++;
if ($visits == 0) {
echo 'I have never seen you before, but I am glad you are here :)';
}
else {
if ($visits == 1) {
echo 'Welcome back! You have been here ', $visits, ' time before';
}
else {
echo 'Welcome back! You have been here ', $visits, ' times before';
}
}
?>
here, $visits is assigned a value in line 3...my doubt is where did this 'visits' come from and when it is not created how is it assigned a default value of 0?
If it's not set $visits will not be zero: it'll be null. However, null==0 so the code works.
The ++ will increment a value. That means getting the value, adding 1 to it, and putting it back. Since null+1 = 1 that works too.
If you were to run this with error_reporting set to include E_NOTICEs, and display_errors on, you would see PHP complaining that the value doesn't exist - only on the first time through, of course.