PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" What do you mean?

3

When a notice occurs, the code may work, but it may not show what we expect.

I think these are the three types of news that we can have most often in PHP.

  •   

    Notice: Undefined variable

  •   

    Notice: Undefined index

  •   

    Notice: Undefined offset

What do these three news mean and what could generate them?

Note:

This question exists in OS in English , the idea is to have a good answer also in Spanish that helps to understand problems that PHP shows us always in English.

    
asked by A. Cedano 16.06.2017 в 13:36
source

3 answers

4

Notice: Undefined variable occurs when you use a variable in an operation, but that variable has not been previously defined. For example:

<?php
    $a1 = "Hola Caracola";
    print_r($a2); // $a2 no se ha definido antes (a veces causado por errores tipográficos)

Notice: Undefined offset occurs when in an array you try to access a numeric index that does not exist in that array. For example:

<?php
    $miArray = array(1,2,3); // 3 posiciones, índices del 0 al 2
    print_r($miArray[3]);    // Acceso al índice 3 que no existe (PHP empieza en 0)

Notice: Undefined index occurs when in an array you try to access an alphanumeric index that does not exist. A couple of examples:

<?php
    $miArray = array(0 => "Hola", "b" => "Caracola");
    print_r($miArray["a"]); // El índice 'a' no existe, sólo '0' o 'b' 

    print_r($_GET["parametroQueNoExisteEnElQueryString"]);
    
answered by 16.06.2017 / 14:56
source
2

Variable: memory space that we reference in php with a name that starts with $ for example $edad could be a variable to save a person's age.

If you try to read (use) a variable before it has been defined, or it is outside of your scope of visibility PHP throws "Undefined variable" .

Example where $b has not been mentioned before set used:

$a = 1;
if($a == 1){
    $a = $b;
}

Example where $b is being referenced outside its scope of visibility:

$a = 1;
if($a == 1){
  $b = 10;
}
$a = $b;

With mentioning the variable, it is already defined, although in general this definition is accompanied by an initialization given that if we define a variable it is logical that it has an initial value that makes sense. The solution is to define the variable before it is used and within the scope of visibility where example is needed: $b before or after $a :

$a = 1;
$b; //Acá ya queda definida pero sin valor inicial
if($a == 1){
...

$a = 1;
$b = 5; //Acá ya queda inicializada (definida + valor inicial)
if($a == 1){
...

Index : is the String that is used as a key to reference a value in an associative array. In this example, first and last name are Index of the associative array $estudiante :

$estudiante['nombre'] = 'Juan';
$estudiante['apellido'] = "Gomez"; 

Undefined Index means that the string that we are passing with Index wanting to read a value from the array does not exist. In the example the Index domicilio does not exist then $dom = $estudiante['domicilio']; throw Undefined Index .

You can verify the existence of an Index with the function array_key_exists($index);

Offset : Similar to Index but for common arrays where the index is an integer that reflects the position (u offset in English) inside the array. When you try to read the value of an array in a position that does not exist we have an Undefined Offset . Example:

$arr[0] = "caballo";
$arr[1] = "tigre";
$animal = $arr[2]; // Undefined Offset

One way to avoid these errors is to verify that the index is greater than 0 and less than the number of array elements ( count($arr) );

    
answered by 16.06.2017 в 15:01
0

First of all a notice I would translate it better as a warning.

Notes are not errors . They are really warnings , and in this case you are simply telling them that these indexes do not exist in the array.

To prevent these messages from coming out on the web you have several options.

Remove in the PHP configuration that shows you the notice

Edit the php.ini and find the error_reporting directive

Just above you will have the explanation of exactly what it means. In my case in production for example I have indicated this:

error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_WARNING & ~E_NOTICE

There I indicate that I want all the errors, but that I do not want neither the notices of deprecated functions, nor the warnings of strict, nor the warnings, nor the notices.

Disable the notices in each php file

In each php file, you will have to execute this function so that it does not show you these errors in the web page that generates the php.

error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_WARNING & ~E_NOTICE);

Schedule correctly by detecting whether or not it exists

In php there is a function called isset() that simply returns if the variable is defined and is not null.

Instead of directly using an array with an index such as $arr['indice'] , you can create a variable that depends on whether or not the previous index in the array has value or not. That variable $ index will no longer give a notice because it will always have value.

$indice = ( isset($arr['indice'] ) ? $arr['indice'] : '';

The previous line of code also means:

if ( isset($arr['indice'] ) {
   $indice = $arr['indice'];
} else {
   $indice = '':
}
    
answered by 27.06.2017 в 17:54