Aviso de PHP: Desplazamiento indefinido: 1 con matriz al leer datos


Estoy recibiendo este error de PHP:

PHP Notice:  Undefined offset: 1

Aquí está el código PHP que lo lanza:

$file_handle = fopen($path."/Summary/data.txt","r"); //open text file
$data = array(); // create new array map

while (!feof($file_handle) ) {
    $line_of_text = fgets($file_handle); // read in each line
    $parts = array_map('trim', explode(':', $line_of_text, 2)); 
    // separates line_of_text by ':' trim strings for extra space
    $data[$parts[0]] = $parts[1]; 
    // map the resulting parts into array 
    //$results('NAME_BEFORE_:') = VALUE_AFTER_:
}

¿Qué significa este error? ¿Qué causa este error?

Author: Eric Leschinski, 2013-07-03

6 answers

Cambiar

$data[$parts[0]] = $parts[1];

A

if ( ! isset($parts[1])) {
   $parts[1] = null;
}

$data[$parts[0]] = $parts[1];

O simplemente:

$data[$parts[0]] = isset($parts[1]) ? $parts[1] : null;

No todas las líneas de su archivo tienen dos puntos en él y, por lo tanto, explotar en él devuelve una matriz de tamaño 1.

Según php.net posibles valores de retorno desde explode:

Devuelve un array de cadenas creado dividiendo el parámetro string en límites formados por el delimitador.

Si delimiter es una cadena vacía (""), explode() devolverá FALSE. Si delimiter contiene un valor que no está contenido en string y se usa un límite negativo, luego se devuelve un array vacío, de lo contrario se devuelve un array que contiene string.

 88
Author: GGio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-10 03:03:36

Cómo reproducir el error anterior en PHP:

php> $yarr = array(3 => 'c', 4 => 'd');

php> echo $yarr[4];
d

php> echo $yarr[1];
PHP Notice:  Undefined offset: 1 in 
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) : 
eval()'d code on line 1

¿Qué significa ese mensaje de error?

Significa que el compilador php buscó la clave 1 y ejecutó el hash contra ella y no encontró ningún valor asociado con ella, luego dijo Undefined offset: 1

¿Cómo hago que desaparezca ese error?

Pregunte a la matriz si la clave existe antes de devolver su valor de esta manera:

php> echo array_key_exists(1, $yarr);

php> echo array_key_exists(4, $yarr);
1

Si la matriz no contiene su clave, no pregunte por su valor. Aunque esta solución hace doble trabajo para su programa para "comprobar si está allí" y luego "ir a buscarlo".

Solución alternativa que es más rápida:

Si obtener una clave que falta es una circunstancia excepcional causada por un error, es más rápido simplemente obtener el valor (como en echo $yarr[1];), y atrapar ese error de desplazamiento y manejarlo de la siguiente manera: https://stackoverflow.com/a/5373824/445131

 19
Author: Eric Leschinski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:37

Este es un "Aviso de PHP", por lo que en teoría podría ignorarlo. Change php.ini:

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

A

error_reporting = E_ALL & ~E_NOTICE

Esto muestra todos los errores, excepto los avisos.

 0
Author: Orijmm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-15 03:54:30

Hace poco tuve este problema y ni siquiera creí que fuera mi error:

Array("Semester has been set as active!", true)
Array("Failed to set semester as active!". false)

Y en realidad lo fue! Acabo de escribir accidentalmente " ." en lugar de ","...

 0
Author: Erikas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-30 18:42:07

Ocultar las advertencias de php en el archivo

error_reporting(0);
 -1
Author: Vitalicus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-08 19:34:48

También puede intentar eliminar la advertencia...

error_reporting=0
 -5
Author: Sagar Kubavat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-21 10:34:58