Consider this PHP script executed on a web server for a single HTTP request:
<?php
$counter = 0;
function increment() {
global $counter;
$counter++;
echo $counter . "\n";
}
increment();
increment();
?>What will be printed when this script runs?
<?php $counter = 0; function increment() { global $counter; $counter++; echo $counter . "\n"; } increment(); increment(); ?>
Remember that PHP variables do not keep their values between requests unless stored externally.
The variable $counter starts at 0 each time the script runs. The function increments it twice, printing 1 then 2.
Which statement best describes how PHP manages variables across multiple HTTP requests?
Think about what happens when you refresh a PHP page multiple times.
PHP runs each request in a new process or thread, so all variables are reset unless saved in sessions, databases, or files.
Look at this PHP code snippet:
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 1;
} else {
$_SESSION['count'] = 1;
}
echo $_SESSION['count'];
?>Why does it always print 1 even after refreshing the page multiple times?
Check what happens inside the if and else blocks.
The code sets $_SESSION['count'] to 1 regardless of whether it existed before, so it never increments.
Which of the following PHP code snippets correctly initializes a variable fresh for each HTTP request and then prints it?
Remember that static variables keep their value during the script execution but are reset on new requests.
Option D initializes $count to 0 each request, then increments and prints 1. Option D causes a syntax error because static variables cannot be declared outside functions. Option D uses global without prior declaration. Option D increments an undefined variable causing a warning.
You want to keep a counter that increases every time a PHP page is loaded, but you cannot use sessions. Which approach below will correctly persist the counter across requests?
Think about where data can be saved outside the PHP process.
Static, global, or local variables reset on each request. Only external storage like files or databases can persist data across requests without sessions.