- How do I fix «Undefined variable» error in PHP?
- 8 Answers 8
- Исправление ошибки «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
- Undefined variable problem with PHP function
- 5 Answers 5
- PHP — Undefined variable
- 9 Answers 9
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.
Исправление ошибки «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
Undefined variable problem with PHP function
Anyway, when I try this code I always get an error message saying that there’s a error on on line 11 (the bold part of the code) and no variable is echoed. I’m guessing that it gives me that error because my variable isn’t defined inside of that function, but I need to define it outside of the function so is there a way to do this?
Use formatting functions so we can actually see your code without problems, it makes it easier to help.
Incidentally, you’d probably benefit from working through the PHP manual’s tutorial section, as it covers a lot of these sort of issues.
5 Answers 5
This is because you’re using the $pera variable (which exists only in the global scope) inside a function.
You could fix this by adding global $pera; within your function, although this isn’t a particularly elegant approach, as global variables are shunned for reasons too detailed to go into here. As such, it would be better to accept $pera as an argument to your function as follows:
function provera($prom, $pera)< if (preg_match("/[0-9\,\.\?\>\.\ >
I tried using $pera as a function argument, but now I’m getting errors that my second argument for provera() is missing and that $pera is unidentified.
@Mentalhead — My apologies — when you call the function you need to supply the variable as a parameter. i.e.: provera($ime, $pera); and provera($prezime, $pera); . Hope this helps.
PHP — Undefined variable
I’m doing some exercises from Beginners PHP & MySQL by Mr. Tucker. On his example everything works fine, but on my PC there is an error:
> // END Secure Connection Script > $thisScriptName = "loginForm.php"; echo 'Login Form
'; $username = $_POST['username']; if(isset($username)) < $password = $_POST['password']; echo "username = " . $username . "
"; echo "password = " . $password . "
"; < // SELECT password for this user from the DB and see it it matches $tUser_SQLselect = "SELECT password FROM tUser "; $tUser_SQLselect .= "WHERE username = '" . $username . "' "; $tUser_SQLselect_Query = mysql_query($tUser_SQLselect); while ($row = mysql_fetch_array($tUser_SQLselect_Query, MYSQL_ASSOC)) < $passwordRetrieved = $row['password']; >mysql_free_result($tUser_SQLselect_Query); echo "passwordRetrieved = ".$passwordRetrieved."
"; if (!empty($passwordRetrieved) AND ($password == $passwordRetrieved)) < echo "YES. Password matches.
"; echo 'Logout'; > else < echo "Access denied.
"; echo 'Try again'; > > > else < echo ''; > echo '--------- END Login Form --------
'; ?>
9 Answers 9
Just before while where you set variable $passwordRetrieved declare it so it should look like this:
$tUser_SQLselect_Query = mysql_query($tUser_SQLselect); $passwordRetrieved = ""; while ($row = mysql_fetch_array($tUser_SQLselect_Query, MYSQL_ASSOC))
Does it not mean that my $passwordRetrieved is an empty string? Where it should take this value from the form?
That’s because your query returned nothing and your
while ($row = mysql_fetch_array($tUser_SQLselect_Query, MYSQL_ASSOC))
You can disable E_NOTICE notices because it’s not something that would hurt
while ($row = mysql_fetch_array($tUser_SQLselect_Query, MYSQL_ASSOC))
while ($row = mysql_fetch_array($tUser_SQLselect_Query, MYSQL_ASSOC))
this is the only place where a value may be assigned to the variable $passwordRetrieved .
If there is no record in the result set the body of the while-loop is never executed and therefore no value ever is assigned to $passwordRetrieved and therefore $passwordRetrieved does not exist/is undefined at line 39 -> Notice: Undefined variable: passwordRetrieved in C:\wamp\www\loginForm.php on line 39 .
You are trying to access the variable $passwordRetrieved when it has not yet been given a value. The access is done here:
echo "passwordRetrieved = ".$passwordRetrieved."
";
The variable would be set just above:
while ($row = mysql_fetch_array($tUser_SQLselect_Query, MYSQL_ASSOC)) < $passwordRetrieved = $row['password']; // VARIABLE SET HERE >
The important thing is that the variable only gets set if the query returns a matching row (i.e., on a successful login). If the login is not valid, the variable is not set.
To check if a variable is set without getting a notice, you would use either isset or empty (there are subtle differences, but as a rule of thumb you can use either most of the time). Your code actually already does this just below:
// Checking if $passwordRetrieved has been set using empty() if (!empty($passwordRetrieved) AND ($password == $passwordRetrieved))