Consider the following PHP code that uses a static variable inside a function. What will be printed after running the script?
<?php function counter() { static $count = 0; $count++; echo $count . ' '; } counter(); counter(); counter(); ?>
Static variables keep their value between function calls.
The static variable $count is initialized only once. Each call increments it, so the output is 1 2 3 .
In PHP, what happens to all variables after the script finishes running?
Think about how PHP runs scripts for each request.
PHP runs scripts fresh each time. After execution, all variables are cleared from memory and reset.
Look at this PHP code snippet. It is intended to print 1 2 3 but prints 1 1 1 instead. Why?
<?php function counter() { $count = 0; $count++; echo $count . ' '; } counter(); counter(); counter(); ?>
Check how the variable $count is declared inside the function.
The variable $count is a normal local variable, so it resets to 0 every time the function runs. It never remembers previous values.
This PHP script uses a session variable to count visits. What will it output on the third page load?
<?php session_start(); if (!isset($_SESSION['visits'])) { $_SESSION['visits'] = 0; } $_SESSION['visits']++; echo $_SESSION['visits']; ?>
Session variables keep data between page loads for the same user.
The session variable visits increments each time the page loads. On the third load, it will be 3.
Which statement best describes how PHP manages memory and variables between separate script executions in a typical web server environment?
Think about how PHP runs scripts on a web server for each request.
PHP runs each script independently with a clean memory state. Variables only persist if saved in sessions, files, or databases.