How to reproduce the above error in 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
What does that error message mean?
It means the php compiler looked for the key 1 and ran the hash against it and didn’t find any value associated with it then said Undefined offset: 1
How do I make that error go away?
Ask the array if the key exists before returning its value like this:
php> echo array_key_exists(1, $yarr);
php> echo array_key_exists(4, $yarr);
1
If the array does not contain your key, don’t ask for its value. Although this solution makes double-work for your program to «check if it’s there» and then «go get it».
Alternative solution that’s faster:
If getting a missing key is an exceptional circumstance caused by an error, it’s faster to just get the value (as in echo $yarr[1];), and catch that offset error and handle it like this: https://stackoverflow.com/a/5373824/445131
Notice: Undefined offset
This error means that within your code, there is an array and its keys. But you may be trying to use the key of an array which is not set.
The error can be avoided by using the isset() method. This method will check whether the declared array key has null value or not. If it does it returns false else it returns true for all cases.
This type of error occurs with arrays when we use the key of an array, which is not set.

In the following, given an example, we are displaying the value store in array key 1, but we did not set while declaring array “$colorarray.”
Error Example:
<?php
// Declare an array with key 2, 3, 4, 5
$colorarray = array(2=>'Red',3=>'Green',4=>'Blue',5=>'Yellow');
// Printing the value of array at offset 1.
echo $colorarray[1];
?>
Output:
Notice: Undefined offset: 1 in index.php on line 5
Here are two ways to deal with such notices.
- Resolve such notices.
- Ignore such notices.
Fix Notice: Undefined offset by using isset() Function
Check the value of offset array with function isset(), empty(), and array_key_exists() to check if key exist or not.
Example:
<?php
$colorarray = array(2=>'Red',3=>'Green',4=>'Blue',5=>'Yellow');
// isset() function to check value at offset 1 of array
if(isset($colorarray[1])){echo $colorarray[1];}
// empty() function to check value at offset 1 of array
if(!empty($colorarray[1])){echo $colorarray[1];}
// array_key_exists() of check if key 1 is exist or not
echo array_key_exists(1, $colorarray);
?>
How to Ignore PHP Notice: Undefined offset?
You can ignore this notice by disabling reporting of notice with option error_reporting.
1. Disable Display Notice in php.ini file
Open php.ini file in your favourite editor and search for text “error_reporting” the default value is E_ALL. You can change it to E_ALL & ~E_NOTICE.
By default:
error_reporting = E_ALL
Change it to:
error_reporting = E_ALL & ~E_NOTICE
Now your PHP compiler will show all errors except ‘Notice.’
2. Disable Display Notice in PHP Code
If you don’t have access to make changes in the php.ini file, In this case, you need to disable the notice by adding the following code on the top of your php page.
<?php error_reporting (E_ALL ^ E_NOTICE); ?>
Now your PHP compiler will show all errors except ‘Notice.’
Improve Article
Save Article
Improve Article
Save Article
The Offset that does not exist in an array then it is called as an undefined offset. Undefined offset error is similar to ArrayOutOfBoundException in Java. If we access an index that does not exist or an empty offset, it will lead to an undefined offset error.
Example: Following PHP code explains how we can access array elements. If the accessed index is not present then it gives an undefined offset error.
php
<?php
$students = array(
0 => 'Rohan',
1 => 'Arjun',
2 => 'Niharika'
);
echo $students[0];
echo $students[5];
echo $students[key];
?>
Output:


There are some methods to avoid undefined offset error that are discussed below:
- isset() function: This function checks whether the variable is set and is not equal to null. It also checks if array or array key has null value or not.
Example:
php
<?php
$students = array(
0 => 'Rohan',
1 => 'Arjun',
2 => 'Niharika'
);
if(isset($students[5])) {
echo $students[5];
}
else {
echo "Index not present";
}
?>
Output:
Index not present
- empty() function: This function checks whether the variable or index value in an array is empty or not.
php
<?php
$students = array(
0 => 'Rohan',
1 => 'Arjun',
2 => 'Niharika'
);
if(!empty($students[5])) {
echo $students[5];
}
else {
echo "Index not present";
}
?>
Output:
Index not present
Example:
php
<?php
function Exists($index, $array) {
if (array_key_exists($index, $array)) {
echo "Key Found";
}
else{
echo "Key not Found";
}
}
$array = array(
"ram" => 25,
"krishna" => 10,
"aakash" => 20
);
$index = "aakash";
print_r(Exists($index, $array));
?>
Output:
Key Found
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
if ($GET['cat'] == 'read') $y=date("Y"); else $y=$GET['cat'] ; if ($GET['alb'] == 'read') $m=date("m"); else $m=$GET['alb'] ; if (!isset($y) OR $y < 1970 OR $y > 2037) $y=date("Y"); if (!isset($m) OR $m < 1 OR $m > 12) $m=date("m"); include_once './libs/mysql.php'; $res=''; $rows=''; $date_array = array(); $arraycount=1; /*Получаем из базы данных все записи */ $res = mysqlQuery("SELECT * FROM `". BG_DBPREFIX ."calendar` WHERE YEAR(date)=".$y." AND MONTH(date)=".$m." ORDER BY date ASC" ); if(mysql_num_rows($res) > 0) // Если записи есть, вытаскиваем по одной в цикле { while($rows = htmlChars(mysql_fetch_assoc($res))) // попутно обрабатывая функцией htmlChars() { $date_array[$arraycount]['id']=$rows['id']; $date_array[$arraycount]['date']=$rows['date']; $date_array[$arraycount]['name']=$rows['name']; $date_array[$arraycount]['status']=$rows['status']; $arraycount++; }; } $prev_y=date('Y',mktime (0,0,0,$m-1,1,$y)); $prev_m=date('m',mktime (0,0,0,$m-1,1,$y)); $next_y=date('Y',mktime (0,0,0,$m+1,1,$y)); $next_m=date('m',mktime (0,0,0,$m+1,1,$y)); echo "<a href="".href('cat='.$prev_y,'alb='.$prev_m)."">Prev</a>"; echo "<a href="".href('cat='.$next_y,'alb='.$next_m)."">Next</a>"; |
Я получаю эту ошибку PHP:
PHP Notice: Undefined offset: 1
Вот код PHP, который его выдает:
$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_:
}
Что означает эта ошибка? Что вызывает эту ошибку?
Ответ 1
Измените
$data[$parts[0]] = $parts[1];
к
if ( ! isset($parts[1])) {
$parts[1] = null;
}
$data[$parts[0]] = $parts[1];
или просто:
$data[$parts[0]] = isset($parts[1]) ? $parts[1] : null;
Не каждая строка вашего файла имеет в ней двоеточие и, следовательно, взорвалась, он возвращает массив размером 1.
В соответствии с php.net возможно вернуть значения из explode:
Возвращает массив строк, созданный путем разделения параметра строки на границах, образованных разделителем.
Если разделителем является пустая строка («»), explode() вернет FALSE. Если разделитель содержит значение, которое не содержится в строке, и используется отрицательный предел, возвращается пустой массив , иначе возвращается массив, содержащий строку.
Ответ 2
Как воспроизвести приведенную выше ошибку в 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
Что означает это сообщение об ошибке?
Это означает, что компилятор php ищет ключ 1 и запускает хэш против него и не нашел никакого значения, связанного с ним, а затем сказал Undefined offset: 1
Как удалить эту ошибку?
Задайте массив, если ключ существует, прежде чем вернуть его значение следующим образом:
php> echo array_key_exists(1, $yarr);
php> echo array_key_exists(4, $yarr);
1
Если массив не содержит ваш ключ, не запрашивайте его значение. Хотя это решение делает двойную работу для вашей программы «проверять, есть ли она там», а затем «пойдите».
Альтернативное решение, которое быстрее:
Если получение отсутствующего ключа является исключительным обстоятельством, вызванным ошибкой, быстрее получить значение (как в echo $yarr[1];) и уловить эту ошибку смещения и обработать ее следующим образом: fooobar.com/questions/123747/…
Ответ 3
Это «Уведомление PHP», поэтому вы могли бы теоретически игнорировать его. Измените php.ini:
error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
Для
error_reporting = E_ALL & ~E_NOTICE
Показывать все ошибки, кроме уведомлений.
Ответ 4
У меня только недавно была эта проблема, и я даже не думал, что это был мой заблуждение:
Array("Semester has been set as active!", true)
Array("Failed to set semester as active!". false)
И на самом деле это было! Я просто случайно набрал «.«, а не «,«…
Ответ 5
Скрыть php предупреждения в файле
error_reporting(0);
Ответ 6
мое самое быстрое решение состояло в том, чтобы минус 1 к длине массива как
$len = count($data);
for($i=1; $i<=$len-1;$i++){
echo $data[$i];
}
мое смещение всегда было последним значением, если число было 140, тогда оно скажет offset 140 но после использования минус 1 все было в порядке
Ответ 7
Идеальное решение было бы как ниже. Вы не пропустите значения от 0 до n.
$len=count($data);
for($i=0;$i<$len;$i++)
echo $data[$i]. "<br>";
Ответ 8
вы также можете попытаться удалить предупреждение…
error_reporting=0