A PHP global variable is empty inside a function, or loses its value
Warning: Undefined variable $count in /var/www/html/index.php on line 8Short answer
PHP has only two scopes: the global scope and the scope of each function. A variable from outside is not visible inside a function unless you pass it in or declare it global, and a variable created inside is gone when the function ends. A value that must survive between page loads needs a session or a database, not a global.
Fix it fast
1Find out which cause you have
Print where the variable is defined and where it is read, and compare the two scopes. This small test shows at once which side of a function call the value is on.
<?php $count = 5; // global scope function show() { var_dump(isset($count)); // false: this is a different, local $count var_dump(isset($GLOBALS['count'])); // true: the global one } show();2Match what you see, then jump to its fix
- 1
Warning: Undefined variable $count inside the function, while the same variable works outside itA global variable is read inside a function without being passed inFix - 2
The variable is defined and printed inside the function, and is undefined after the callA value is set inside a function but read outside itFix - 3
A config or helper file defines variables, and they are undefined outside the function that included itA file was included from inside a functionFix - 4
A local counter starts from zero on every call of the functionThe value needs to live longer than one function callFix - 5
The variable is right during one request and back to its starting value after a reloadThe value should survive the next page load, but PHP starts fresh each requestFix
- 1
What does the error look like?
Warning: Undefined variable $count in /var/www/html/index.php on line 8A variable set at the top of the file prints nothing inside a functionA counter set in one request is back to its start on the next page load
Cause 1 of 5
A global variable is read inside a function without being passed in
1Check
Any variable defined outside a function belongs to the global scope. Inside a function, the same name refers to a new local variable that has no value. The manual says that in PHP a global must be declared global inside a function to be used there.
grep -n "function" index.php2Fix
Pass the value as an argument, which is the clearest option. If you must use the global, declare it with global, or read it through $GLOBALS.
<?php
$count = 5;
function double_it(int $n): int {
return $n * 2;
}
echo double_it($count);
// or
function show() {
global $count;
echo $count;
}3Verify
Run the file. The function now prints 5 or 10, and the warning is gone.
php index.phpConfirmed by php.net
Cause 2 of 5
A value is set inside a function but read outside it
1Check
A variable created inside a function is limited to that function's body, so it is gone when the function returns. Only a variable declared global, or written through $GLOBALS, reaches the outside.
php -r 'function f(){ $x = 1; } f(); var_dump(isset($x));'2Fix
Return the value and assign it at the call site. Use global or $GLOBALS only when you cannot change the function signature.
<?php
function load_total(): int {
$total = 42;
return $total;
}
$total = load_total();
echo $total;3Verify
The value prints after the call.
php index.phpConfirmed by php.net
Cause 3 of 5
A file was included from inside a function
1Check
When a file is included from inside a function, its variables are created as if they were defined in that function, so they are local to it.
grep -rnE "include|require" --include=*.php .2Fix
Include the file at the top level, or inside the included file declare the variables global. The manual notes that the global keyword outside a function is not an error and can be used if the file is included from inside a function.
<?php
// config.php
global $db_host;
$db_host = 'localhost';3Verify
Call the function that includes the file, then check that the variable exists at the top level.
var_dump(isset($db_host));Confirmed by php.net
Cause 4 of 5
The value needs to live longer than one function call
1Check
A normal local variable is created fresh on each call. A static variable stays local to the function, but it keeps its value when execution leaves the function.
php -r 'function c(){ $n = 0; return ++$n; } c(); var_dump(c());'2Fix
Declare the variable static inside the function.
<?php
function next_id(): int {
static $id = 0;
return ++$id;
}
next_id();
echo next_id(); // 23Verify
The second call prints 2.
php index.phpConfirmed by php.net
Cause 5 of 5
The value should survive the next page load, but PHP starts fresh each request
1Check
A plain variable is created when the script runs and is not carried to the next page load. The manual describes sessions as the way to persist state information between page requests, using a session id that is normally sent in a cookie.
curl -s -c jar.txt -b jar.txt http://localhost/counter.php
curl -s -c jar.txt -b jar.txt http://localhost/counter.php2Fix
Keep the value in the session, or in a database if every visitor must share it.
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
echo $_SESSION['count'];3Verify
Run the two curl calls again with the same cookie jar. The second one prints a larger number.
curl -s -c jar.txt -b jar.txt http://localhost/counter.php
curl -s -c jar.txt -b jar.txt http://localhost/counter.phpConfirmed by php.net
How do I stop it coming back?
- Pass values into functions as arguments and return results, so a function never depends on a hidden global.
- Keep configuration in one place, such as a returned array or a small class, and not in loose global variables.
- Turn on error reporting in development, so an undefined variable warning is visible the first time it happens.
- Decide for every value how long it must live: one call (local), one request (global or a property), many requests (session or database).
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Back end
Android gets HTML instead of JSON from a PHP API
org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
The response body is not JSON.
2 causes, each with a fixBack end
Apache returns 403 when a URL contains %3F
a request like /page%3Fname=test is refused while /page?name=test works
Recent Apache httpd blocks a rewrite when the request contains an encoded question mark (%3F) and the rewritten target has a literal ?.
2 causes, each with a fixBack end
Apache returns 500 with Premature end of script headers
500 Internal Server Error
Apache ran your script, but the script printed no valid HTTP header before its output.
3 causes, each with a fixBack end
Apache returns 503 or 504 because PHP-FPM did not answer in time
Error dispatching request
Apache sent the request to PHP-FPM and gave up waiting.
3 causes, each with a fixBack end
AWS SDK for PHP cannot get credentials from the instance profile metadata server
Error retrieving credentials from the instance profile metadata server.
The SDK tries the EC2 instance metadata service when it has no valid credentials from anywhere earlier in its chain.
4 causes, each with a fixBack end
AWS SDK for PHP rejects requests: the signature is from the future
Signature not yet current: {date} is still later than {date}
AWS compares the timestamp in your signed request with its own clock.
2 causes, each with a fix