PHP - Notice: Undefined variable error
The Mistake Undefined variable often appears during PHP script execution as a message:Notice: Undefined variable: nom_variable in C:\wamp\www\project\index.php on line 14ca what does this error mean and how do I fix it?
The Undefined variable error is caused because it is:
- It has not been declared in code.
- It is used in another file that uses the same variable name.
- It has not been initialized.
The isset() detects if the variable exists and initializes. Again, the method empty() is more optimal because it doesn't generate an error message.
Example:
foreach ($array as $item) {The count variable was not set, and in this case the error Undefined variable appears.
// do something
$count++;
}
To fix this, add the count variable before the loop without forgetting the initialization to zero.
$count=0;Example 2:
foreach ($array as $item) {
// do something
$count++;
}
session_start();Don't forget to initialize the session with session_start() otherwise the server will not be able to identify and read the variables $_SESSION.
// recommended solution
$nom = $_SESSION['nom_utilisateur'];
if (empty($nom_user)) $nom_user = '';
Or
// set the variable at the beginning of index.php
$nom = '';
$nom = $_SESSION['nom_utilisateur'];
Or
$nom = $_SESSION['nom_utilisateur'];
if (!isset($nom_user)) $nom_user = '';
Resources:
http://php.net/manual/en/function.empty.php
PHP: "Notice: Undefined variable"