Undefined variable php ошибка

Почему возникает ошибка

Ошибка undefined variable появляется при попытке обратиться к не существующей (не объявленной ранее) переменной:

<?php
echo $text;

Если в настройках PHP включено отображение ошибок уровня E_NOTICE, то при запуске этого кода в браузер выведется ошибка:

Notice: Undefined variable: text in D:ProgramsOpenServerdomainstest.localindex.php on line 2

Как исправить ошибку

Нужно объявить переменную перед обращением к ней:

$a = '';
echo $a;

Нет уверенности, что переменная будет существовать? Можно указать значение по-умолчанию:

<?php
if(!isset($text))
    $text = '';

echo $text;

Или сокращённые варианты:

<?php
// С оператором объединения с null (PHP 7+)
$text = $text ?? '';

// С оператором присваивания значения null (PHP 7.4+)
$text ??= '';

Есть ещё один вариант исправления этой ошибки — отключить отображение ошибок уровня E_NOTICE:

<?php
error_reporting(E_ALL & ~E_NOTICE);
echo $a; // Ошибки не будет

Не рекомендую этот вариант. Скрытие ошибок вместо их исправления — не совсем правильный подход.

Кроме этого, начиная с PHP 8 ошибка undefined variable перестанет относиться к E_NOTICEи так легко отключить её уже не удастся.

Если ошибка появилась при смене хостинга

Часто ошибка возникает при переезде с одного сервера на другой. Практически всегда причина связана с разными настройками отображения ошибок на серверах.

По-умолчанию PHP не отображает ошибки уровня E_Notice, но многие хостинг-провайдеры предпочитают настраивать более строгий контроль ошибок. Т.е. на старом сервере ошибки уже были, но игнорировались сервером, а новый сервер таких вольностей не допускает.

Остались вопросы? Добро пожаловать в комментарии. :)

This error message is meant to help a PHP programmer to spot a typo or a mistake when accessing a variable (or an array element) that doesn’t exist. So a good programmer:

  1. Makes sure that every variable or array key is already defined by the time it’s going to be used. In case a variable is needed to be used inside a function, it must be passed to that function as a parameter.
  2. Pays attention to this error and proceeds to fix it, just like with any other error. It may indicate a spelling error or that some procedure didn’t return the data it should.
  3. Only on a rare occasion, when things are not under the programmer’s control, a code can be added to circumvent this error. But by no means it should be a mindless habit.

Notice / Warning: Undefined variable

Although PHP does not require a variable declaration, it does recommend it in order to avoid some security vulnerabilities or bugs where one would forget to give a value to a variable that will be used later in the script. What PHP does in the case of undeclared variables is issue an error of E_WARNING level.

This warning helps a programmer to spot a misspelled variable name or a similar kind of mistake (like a variable was assigned a value inside of a condition that evaluated to false). Besides, there are other possible issues with uninitialized variables. As it’s stated in the PHP manual,

Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name.

Which means that a variable may get a value from the included file, and this value will be used instead of null that one expects accessing a non-initialized variable, which may lead to unpredictable results. To avoid that, all variables in a PHP file are best to be initialized before use.

Ways to deal with the issue:

  1. Recommended: Declare every variable before use. This way you will see this error only when you actually make a mistake, trying to use a non-existent variable — the very reason this error message exists.

     //Initializing a variable
     $value = ""; //Initialization value; 0 for int, [] for array, etc.
     echo $value; // no error
     echo $vaule; // an error pinpoints a misspelled variable name
    
  • a special case when a variable is defined but is not visible in a function. Functions in PHP have own variable scope, and if you need to use in a function a variable from outside, its value must be passed as a function’s parameter:

    function test($param) {
        return $param + 1; 
    }
    $var = 0;
    echo test($var); // now $var's value is accessible inside through $param
    
  1. Suppress the error with null coalescing operator. But remember that this way PHP won’t be able to notify you about using wrong variable name.

     // Null coalescing operator
     echo $value ?? '';
    

    For the ancient PHP versions (< 7.0) isset() with ternary can be used

     echo isset($value) ? $value : '';
    

    Be aware though, that it’s still essentially an error suppression, though for just one particular error. So it may prevent PHP from helping you by marking an unitialized variable.

  2. Suppress the error with the @ operator. Left here for the historical reasons but seriously, it just shouldn’t happen.

Note: It’s strongly recommended to implement just point 1.

Notice: Undefined index / Undefined offset / Warning: Undefined array key

This notice/warning appears when you (or PHP) try to access an undefined index of an array.

Internal arrays

When dealing with internal arrays, that are defined in your code, the attitude should be exactly the same: just initialize all keys before use. this way this error will do its intended job: notify a programmer about a mistake in their code. So the approach is the same:

Recommended: Declare your array elements:

    //Initializing a variable
    $array['value'] = ""; //Initialization value; 0 for int, [] for array, etc.
    echo $array['value']; // no error
    echo $array['vaule']; // an error indicates a misspelled key

A special case is when some function returns either an array or some other value such as null or false. Then it has to be tested before trying to access the array elements, such as

$row = $stmt->fetch();
if ($row) { // the record was found and can be worked with
    echo $row['name']; 
}

Outside arrays

With outside arrays (such as $_POST / $_GET / $_SESSION or JSON input) the situation is a bit different, because programmer doesn’t have the control over such arrays’ contents. So checking for some key existence or even assigning a default value for a missing key could be justified.

  • when a PHP script contains an HTML form, it is natural that on the first load there is no form contents. Therefore such a script should check if a form was submitted

      // for POST forms check the request method
      if ($_SERVER['REQUEST_METHOD'] === 'POST') {
          // process the form
      }
      // for GET forms / links check the important field
      if (isset($_GET['search'])) {
          // process the form
      }
    
  • some HTML form elements, such as checkboxes, aren’t sent to the server if not checked. In this case it is justified to use a null coalescing operator to assign a default value

      $agreed = $_POST['terms'] ?? false;
    
  • optional QUERY STRING elements or cookies should be treated the same way

      $limit = $_GET['limit'] ?? 20;
      $theme = $_COOKIE['theme'] ?? 'light';
    

But assignments should be done at the very beginning of the script. Validate all input, assign it to local variables, and use them all the way in the code. So every variable you’re going to access would deliberately exist.

Related:

  • Notice: Undefined variable
  • Notice: Undefined Index

  John Mwaniki /   10 Dec 2021

This error, as it suggests, occurs when you try to use a variable that has not been defined in PHP.

Example 1

<?php
echo $name;
?>

Output

Notice: Undefined variable: name in /path/to/file/file.php on line 2.

Example 2

<?php
$num1 = 27;
$answer = $num1 + $num2;
echo $answer;
?>

Output

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

isset($variable)

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

<?php
//Example 1
$name = "Raju Rastogi";
if(isset($name)){
  $result = "The name is $name";
}
else{
  $result = "The name has not been set";
}
echo $result;
//Output: The name is Raju Rastogi
echo "<br>"


//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.

<?php
$name = "Farhan Qureshi";
echo $name;
//Output: Farhan Qureshi
?>

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.

<?php
$num1 = 27;
if(isset($num1) && isset($num2)){
$answer = $num1 + $num2;
echo $answer;
}
?>

The addition operation will not take place because one of the required variables ($num2) has not been set.

<?php
$num1 = 27;
$num2 = 8;
if(isset($num1) && isset($num2)){
$answer = $num1 + $num2;
echo $answer;
}
//Oputput: 35
?>

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

<?php
$name = "John Doe";
$name = isset($name) ? $name : '';
$age= isset($age) ? $age: 0;
echo "My name is $name and I am $age yrs old.";
//Output: My name is John Doe and I am 0 yrs old.
?>

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

Replace it with:

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.

11.03.2021

Марат

51

0

php | php_error |

undefined variable или как исправить ошибку «undefined variable» -я даже и забыл, что такой вид ошибки существует!

Подробно об ошибке «undefined variable«

  1. undefined variable
  2. Как выключить ошибку undefined variable
  1. Notice undefined variable

    Что означает «Notice undefined variable» — начнем с перевода… Когда вы встречаете разного рода ошибки — просто переведите данную ошибку — потому, что ошибка она на то и ошибка, что в смысле этой ошибки и есть ответ.

    Notice — переводится как :

    уведомление, внимание, объявление, нотис сущ
    замечать, уведомлять, обращать внимание гл

    undefined — переводится как :

    неопределенный прил

    variable — переводится как :

    переменная сущ
    изменчивый прил
    регулируемый, изменяющийся прич

    Итого, если суммировать и перевести с русского на русский:

    «Notice undefined variable» — внимание! Неопределенная переменная…

    Т.е. вы выводите переменную, которая не существует! Вообще — это очень неудобная ошибка, я её просто выключил!

    Пример возникновения «undefined variable»

    Самый простой пример… возникновения ошибки «undefined variable«. Переменная ранее не была создана и выводим таким образом с помощью echo:

    echo $example_var;

    Для предотвращения такого рода ошибки, выше echo нужно создать данную переменную:

    $example_var = »;

    echo $example_var;

  2. Как выключить ошибку undefined variable

    Почему я написал выше, что я забыл, что вообще существует такой вид ошибки, как «» — да просто потому, что я каждый день не покупаю новый хостинг, а нахожусь уже на одном хостинге ruweb — 10 лет

    И у меня с самого начала, данная ошибка была отключена.

    Но если у вас не так.
    Стоит ли отключать вывод ошибки undefined variable.

    По этому поводу — всегда будут два мнения за и против.

    Я отключаю, потому, что мне не нужна именно эта ошибка.

    Смотри как отключить ошибки, или как показывать ошибки, только админу.

Не благодарите, но ссылкой можете поделиться!

COMMENTS+

 
BBcode


В логах получаю ошибку PHP Notice: Undefined variable: col in
вот код:
<div class="col-sm-<?php echo $col; ?>">

Как это исправить? Понял, что отвечает за шаблон.


  • Вопрос задан

    более года назад

  • 258 просмотров

$col не инициализирована!
Где-то ранее в вашем коде, когда вы её только объявляете,
напишите значение по умолчанию. Например $col = 12;

И нет надобности выводить через echo, есть более короткая запись для таких случаев:
<?php=$col;?>
или (если поддерживается short_open_tags
<?=$col;?>

Undefined variable в переводе с английского означает, что такой переменной нет.
Это значит что ошибка в логике, попытка вывести переменную, которой не было присвоено никакое значение.
Соответственно, эту логическую ошибку надо исправить — либо присвоить какое-то значение, либо не выводить.

Пригласить эксперта


  • Показать ещё
    Загружается…

22 июн. 2023, в 10:00

2500 руб./за проект

22 июн. 2023, в 09:55

1000 руб./за проект

22 июн. 2023, в 09:29

500 руб./за проект

Минуточку внимания

  • Undefined near line 1 column 1 octave ошибка
  • Undefined is not a function ошибка
  • Undefined index php ошибка
  • Undefined index name ошибка
  • Undeclared identifier ошибка делфи