- Исправление ошибки «Notice: undefined variable» в PHP
- Как исправить ошибку
- Если ошибка появилась при смене хостинга
- [Solved]: Notice: Undefined variable in PHP
- Example 1
- Example 2
- Syntax
- Example
- The Fix for Undefined variable error
- 1. Define your variables before using them
- 2. Validating variables with isset() function
- 3. Setting the undefined variable to a default value
- Example
- 4. Disabling Notice error reporting
- Related Articles
- Check if a variable is undefined in PHP
- 8 Answers 8
- The isset() function does not check if a variable is defined.
- So how do you actually check if a variable is defined? You check the defined variables.
- How do I fix «Undefined variable» error in PHP?
- 8 Answers 8
Исправление ошибки «Notice: undefined variable» в PHP
Ошибка undefined variable появляется при попытке обратиться к не существующей (не объявленной ранее) переменной:
Если в настройках PHP включено отображение ошибок уровня E_NOTICE, то при запуске этого кода в браузер выведется ошибка:
Notice: Undefined variable: text in D:\Programs\OpenServer\domains\test.local\index.php on line 2
Как исправить ошибку
Нужно объявить переменную перед обращением к ней:
Нет уверенности, что переменная будет существовать? Можно указать значение по-умолчанию:
Есть ещё один вариант исправления этой ошибки — отключить отображение ошибок уровня E_NOTICE:
Не рекомендую этот вариант. Скрытие ошибок вместо их исправления — не совсем правильный подход.
Кроме этого, начиная с PHP 8 ошибка undefined variable перестанет относиться к E_NOTICEи так легко отключить её уже не удастся.
Если ошибка появилась при смене хостинга
Часто ошибка возникает при переезде с одного сервера на другой. Практически всегда причина связана с разными настройками отображения ошибок на серверах.
По-умолчанию PHP не отображает ошибки уровня E_Notice, но многие хостинг-провайдеры предпочитают настраивать более строгий контроль ошибок. Т.е. на старом сервере ошибки уже были, но игнорировались сервером, а новый сервер таких вольностей не допускает.
Остались вопросы? Добро пожаловать в комментарии. 🙂
[Solved]: Notice: Undefined variable in PHP
This error, as it suggests, occurs when you try to use a variable that has not been defined in PHP.
Example 1
Notice: Undefined variable: name in /path/to/file/file.php on line 2.
Example 2
Notice: Undefined variable: num2 in /path/to/file/file.php on line 3.
In our above two examples, we have used a total of 4 variables which include $name , $num1 , $num2 , and $answer .
But out of all, only two ($name and $num2) have resulted in the «undefined variable» error. This is because we are trying to use them before defining them (ie. assigning values to them).
In example 1, we are trying to print/display the value of the variable $name, but we had not yet assigned any value to it.
In example 2, we are trying to add the value of $num1 to the value of $num2 and assign their sum to $answer. However, we have not set any value for $num2.
To check whether a variable has been set (ie. assigned a value), we use the in-built isset() PHP function.
Syntax
We pass the variable name as the only argument to the function, where it returns true if the variable has been set, or false if the variable has not been set.
Example
else < $result = "The name has not been set"; >echo $result; //Output: The name is Raju Rastogi echo "
" //Example 2 if(isset($profession)) < $result = "My profession is $profession"; >else < $result = "The profession has not been set"; >echo $result; //Output: The profession has not been set ?>
In our first example above, we have defined a variable ($name) by creating it and assigning it a value (Raju Rastogi) and thus the isset() function returns true.
In our second example, we had not defined our variable ($profession) before passing to the isset() function and thus the response is false.
The Fix for Undefined variable error
Here are some ways in which you can get rid of this error in your PHP program.
1. Define your variables before using them
Since the error originates from using a variable that you have not defined (assigned a value to), the best solution is to assign a value to the variable before using it anywhere in your program.
For instance, in our first example, the solution is to assign a value to the variable $name before printing it.
The above code works without any error.
2. Validating variables with isset() function
Another way to go about this is to validate whether the variables have been set before using them.
The addition operation will not take place because one of the required variables ($num2) has not been set.
The addition this time will take place because the two variables required have been set.
3. Setting the undefined variable to a default value
You can also check whether the variables have been defined using the isset() function and if not, assign them a default value.
For instance, you can set a blank «» value for variables expected to hold a string value, and a 0 for those values expect to hold a numeric value.
Example
4. Disabling Notice error reporting
This is always a good practice to hide errors from the website visitor. In case these errors are visible on the website to the web viewers, then this solution will be very useful in hiding these errors.
This option does not prevent the error from happening, it just hides it.
Open the php.ini file in a text editor, and find the line below:
error_reporting = E_ALL & ~E_NOTICE
Now the ‘NOTICE’ type of errors won’t be shown again. However, the other types of errors will be shown.
Another way of disabling these errors is to add the line of code below on the top of your PHP code.
error_reporting (E_ALL ^ E_NOTICE);
That’s all for this article. It’s my hope that it has helped you solve the error.
Related Articles
Check if a variable is undefined in PHP
I would like to know if we have a similar statement in PHP, not being isset(), but literally checking for an undefined value. Something like: $isTouch != «» Is there something similar as the above in PHP?
I know this is a PHP question but a note about the JS check: if you use myVar !== undefined it will throw a ReferenceError if the variable doesn’t actually exist. Using typeof myVar !== ‘undefined’ doesn’t, so it can be used to check variables that may or may not exist.
8 Answers 8
It will return true if the $variable is defined. If the variable is not defined it will return false .
Note: It returns TRUE if the variable exists and has a value other than NULL, FALSE otherwise.
If you want to check for false , 0 , etc., you can then use empty() —
you could also do this by using the empty() which would return false if it is an empty string. isset() will return true if its an empty string, also empty does a isset check internally.
you could also do this: $isTouch = (bool) $variable; which will do the same as isset() and is maybe a little better since it will work like empty() .
I would argue that !isset(. ) does NOT check whether a value is undefined. It checks if it is either undefined or null. I think it’s important to note that things can be defined as null.
The isset() function does not check if a variable is defined.
It seems you’ve specifically stated that you’re not looking for isset() in the question. I don’t know why there are so many answers stating that isset() is the way to go, or why the accepted answer states that as well.
It’s important to realize in programming that null is something. I don’t know why it was decided that isset() would return false if the value is null.
To check if a variable is undefined you will have to check if the variable is in the list of defined variables, using get_defined_vars() . There is no equivalent to JavaScript’s undefined (which is what was shown in the question, no jQuery being used there).
In the following example it will work the same way as JavaScript’s undefined check.
$isset = isset($variable); var_dump($isset); // false
But in this example, it won’t work like JavaScript’s undefined check.
$variable = null; $isset = isset($variable); var_dump($isset); // false
$variable is being defined as null, but the isset() call still fails.
So how do you actually check if a variable is defined? You check the defined variables.
Using get_defined_vars() will return an associative array with keys as variable names and values as the variable values. We still can’t use isset(get_defined_vars()[‘variable’]) here because the key could exist and the value still be null, so we have to use array_key_exists(‘variable’, get_defined_vars()) .
$variable = null; $isset = array_key_exists('variable', get_defined_vars()); var_dump($isset); // true $isset = array_key_exists('otherVariable', get_defined_vars()); var_dump($isset); // false
However, if you’re finding that in your code you have to check for whether a variable has been defined or not, then you’re likely doing something wrong. This is my personal belief as to why the core PHP developers left isset() to return false when something is null.
This, is the right answer! As for checking if a variable is defined, it’s sometimes useful when working on a shi*y code with global vars all over the place. And why did the PHP folks decide to have isset() return false if the variable is defined and contains null. that’s another mystery on Earth!
Thanks, this marks the end of my boggling at isset() ‘s curious blind-spot for null . As for the «doing something wrong» rationale, after brief consideration I can’t point to a non-sketchy scenario for needing to know if a null variable exists, but for an array member there are most certainly cases of a meaningful null , e.g. when using prepared statements with PDO .
if($test) < echo "Yes 1"; >if(!is_null($test)) < echo "Yes 2"; >$test = "hello"; if($test)
The best way is to use isset(). Otherwise you can have an error like «undefined $test».
You’ll not have any error, because the first condition isn’t accepted.
«The best way is to use isset(). Otherwise you can have an error like «undefined $test».» OP is asking exactly how to check when a variable is undefined! Or when a piece of code will return the warning that you mentioned: probably he wants to intercept such case!
To check if a variable is set you need to use the isset function.
$lorem = 'potato'; if(isset($lorem))< echo 'isset true' . '
'; >else< echo 'isset false' . '
'; > if(isset($ipsum))< echo 'isset true' . '
'; >else< echo 'isset false' . '
'; >
You can use the ternary operator to check whether the value is set by POST/GET or not. Something like this:
$value1 = $_POST['value1'] = isset($_POST['value1']) ? $_POST['value1'] : ''; $value2 = $_POST['value2'] = isset($_POST['value2']) ? $_POST['value2'] : ''; $value3 = $_POST['value3'] = isset($_POST['value3']) ? $_POST['value3'] : ''; $value4 = $_POST['value4'] = isset($_POST['value4']) ? $_POST['value4'] : '';
PHP 7.0 introduced the Null coalescing operator which is designed for things like this. The code is then $value1 = $_POST[«value1»] ?? «fallback» .
You can use the PHP isset() function to test whether a variable is set or not. The isset() will return FALSE if testing a variable that has been set to NULL. Example:
This code will output «This line is printed, because the $var1 is set.»
JavaScript’s ‘strict not equal’ operator ( !== ) on comparison with undefined does not result in false on null values.
var createTouch = null; isTouch = createTouch !== undefined // true
To achieve an equivalent behaviour in PHP, you can check whether the variable name exists in the keys of the result of get_defined_vars() .
// just to simplify output format const BR = '
' . PHP_EOL; // set a global variable to test independence in local scope $test = 1; // test in local scope (what is working in global scope as well) function test() < // is global variable found? echo '$test ' . ( array_key_exists('test', get_defined_vars()) ? 'exists.' : 'does not exist.' ) . BR; // $test does not exist. // is local variable found? $test = null; echo '$test ' . ( array_key_exists('test', get_defined_vars()) ? 'exists.' : 'does not exist.' ) . BR; // $test exists. // try same non-null variable value as globally defined as well $test = 1; echo '$test ' . ( array_key_exists('test', get_defined_vars()) ? 'exists.' : 'does not exist.' ) . BR; // $test exists. // repeat test after variable is unset unset($test); echo '$test ' . ( array_key_exists('test', get_defined_vars()) ? 'exists.' : 'does not exist.') . BR; // $test does not exist. >test();
In most cases, isset($variable) is appropriate. That is aquivalent to array_key_exists(‘variable’, get_defined_vars()) && null !== $variable . If you just use null !== $variable without prechecking for existence, you will mess up your logs with warnings because that is an attempt to read the value of an undefined variable.
However, you can apply an undefined variable to a reference without any warning:
// write our own isset() function function my_isset(&$var) < // here $var is defined // and initialized to null if the given argument was not defined return null !== $var; >// passing an undefined variable by reference does not log any warning $is_set = my_isset($undefined_variable); // $is_set is false
How do I fix «Undefined variable» error in PHP?
Today, I have started to learn PHP. And, I have created my first PHP file to test different variables. You can see my file as follows.
Test variables inside the function:"; echo "Variable x is: $x"; echo "
"; echo "Variable y is: $y"; > myTest(); echo "
Test variables outside the function:
"; echo "Variable x is: $x"; echo "
"; echo "Variable y is: $y"; ?>
Notice: Undefined variable: x in /opt/lampp/htdocs/anand/php/index.php on line 19 Notice: Undefined variable: y in /opt/lampp/htdocs/anand/php/index.php on line 29
8 Answers 8
The first error ( $x is undefined) is because globals are not imported into functions by default (as opposed to «super globals», which are).
You need to tell your function you’re referencing the global variable $x :
function myTest() < global $x; // $x refers to the global variable $y=10; // local scope echo "Test variables inside the function:
"; echo "Variable x is: $x"; echo "
"; echo "Variable y is: $y"; >
Otherwise, PHP cannot tell whether you are shadowing the global variable with a local variable of the same name.
The second error ( $y is undefined), is because local scope is just that, local. The whole point of it is that $y doesn’t «leak» out of the function. Of course you cannot access $y later in your code, outside the function in which it is defined. If you could, it would be no different than a global.