PHP Notice: Undefined offset: 1 with array when reading data - php

I am getting this PHP error:
PHP Notice: Undefined offset: 1
Here is the PHP code that throws it:
$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_:
}
What does this error mean? What causes this error?

Change
$data[$parts[0]] = $parts[1];
to
if ( ! isset($parts[1])) {
$parts[1] = null;
}
$data[$parts[0]] = $parts[1];
or simply:
$data[$parts[0]] = isset($parts[1]) ? $parts[1] : null;
Not every line of your file has a colon in it and therefore explode on it returns an array of size 1.
According to php.net possible return values from explode:
Returns an array of strings created by splitting the string parameter on boundaries formed by the delimiter.
If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.

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

Update in 2020 in Php7:
there is a better way to do this using the Null coalescing operator by just doing the following:
$data[$parts[0]] = $parts[1] ?? null;

This is a "PHP Notice", so you could in theory ignore it. Change php.ini:
error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
To
error_reporting = E_ALL & ~E_NOTICE
This show all errors, except for notices.

my quickest solution was to minus 1 to the length of the array as
$len = count($data);
for($i=1; $i<=$len-1;$i++){
echo $data[$i];
}
my offset was always the last value if the count was 140 then it will say offset 140 but after using the minus 1 everything was fine

The ideal solution would be as below. You won't miss the values from 0 to n.
$len=count($data);
for($i=0;$i<$len;$i++)
echo $data[$i]. "<br>";

In your code:
$parts = array_map('trim', explode(':', $line_of_text, 2));
You have ":" as separator. If you use another separator in file, then you will get an "Undefined offset: 1" but not "Undefined offset: 0" All information will be in $parts[0] but no information in $parts[1] or [2] etc. Try to echo $part[0]; echo $part[1]; you will see the information.

I just recently had this issue and I didn't even believe it was my mistype:
Array("Semester has been set as active!", true)
Array("Failed to set semester as active!". false)
And actually it was! I just accidentally typed "." rather than ","...

The output of the error, is because you call an index of the Array that does not exist, for example
$arr = Array(1,2,3);
echo $arr[3];
// Error PHP Notice: Undefined offset: 1 pointer 3 does not exist, the array only has 3 elements but starts at 0 to 2, not 3!

Related

PHP Array_intersect enters undefined offset

I got an array working like this:
$listaMaterias[x]['id_materia'] = (value with number and letters random)
$listaMaterias[x]['name_materia'] = (string)
$listaEditoriales[x]['id_editorial'] = (value with n. and l. random)
$listaEditoriales[x]['name_editorial'] = (string)
A 'materia' is a book's category. I made a foreach where I get all values from an xml right. Many editorials and materias, where some of them comes repeated.
And then, I make a method with an array_intersect to make remove repeated values, but I get an error :
$listaEdits_result = array(); // final results
$listaMats_result = array();
$listaEds_first_res = $listaEditoriales[0];
for ($j = 1 ; $j < count($listaEditoriales) ; $j++ ){
$listaEdits_result = array_intersect($listaEds_first_res, $listaEditoriales[$j]);
$listaEds_first_res = $listaEdits_result;
}
$listaMts_first_res = $listaMaterias[0];
for ($k = 1 ; $k < count($listaMaterias) ; $k++ ){
// Line 285, is this one above
$listaMats_result = array_intersect($listaMts_first_res, $listaMaterias[$j]);
$listaMts_first_res = $listaMats_result;
}
And finally, I get this error :
Notice: Undefined offset: 20 in [URL]/menu-librosnormales.php on line 285
Warning: array_intersect(): Argument #2 is not an array in [URL]/menu-librosnormales.php on line 285
Why access offset 20 if before I count this quantity in every array :
count($listaEditoriales) : 20
count($listaMaterias) : 14
Instead of $listaMaterias[$j] do $listaMaterias[$k] in second loop below line:-
$listaMats_result = array_intersect($listaMts_first_res, $listaMaterias[$j]);
Note:- If your aim is to remove duplicates from an array then you can use array_unique() easily.
In the second loop you use $listaMaterias[$j] but the loop is indexed by $k, not by $j.
The value of $j is count($listaEditoriales) because this was the last value of $j when the first loop ended. Since $listMaterias contains only 14 items, trying to access its 21st item triggers the notice you described.
If the purpose of each loop is to compute the intersection of the arrays stored in $listaEditoriales (and $listaMaterias) then you can do with a single call to array_intersect() using arguments unpacking (the so-called "splat operator"):
$listaEds_first_res = array_intersect(...$listaEditoriales);
$listaMts_first_res = array_intersect(...$listaMaterias);
The arguments unpacking operator is available since PHP 5.6. If you need to run the code on older PHP versions then you can use call_user_func_array() instead:
$listaEds_first_res = call_user_func_array('array_intersect', $listaEditoriales);
$listaMts_first_res = call_user_func_array('array_intersect', $listaMaterias);
The two lines of code above do the same thing as the entire block of code you posted in the question (faster and without errors).

PHP notices - undefined [duplicate]

I am receiving the following error in PHP
Notice undefined offset 1: in C:\wamp\www\includes\imdbgrabber.php line 36
Here is the PHP code that causes it:
<?php
# ...
function get_match($regex, $content)
{
preg_match($regex,$content,$matches);
return $matches[1]; // ERROR HAPPENS HERE
}
What does the error mean?
If preg_match did not find a match, $matches is an empty array. So you should check if preg_match found an match before accessing $matches[0], for example:
function get_match($regex,$content)
{
if (preg_match($regex,$content,$matches)) {
return $matches[0];
} else {
return null;
}
}
How to reproduce this error in PHP:
Create an empty array and ask for the value given a key like this:
php> $foobar = array();
php> echo gettype($foobar);
array
php> echo $foobar[0];
PHP Notice: Undefined offset: 0 in
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) :
eval()'d code on line 1
What happened?
You asked an array to give you the value given a key that it does not contain. It will give you the value NULL then put the above error in the errorlog.
It looked for your key in the array, and found undefined.
How to make the error not happen?
Ask if the key exists first before you go asking for its value.
php> echo array_key_exists(0, $foobar) == false;
1
If the key exists, then get the value, if it doesn't exist, no need to query for its value.
Undefined offset error in PHP is Like 'ArrayIndexOutOfBoundException' in Java.
example:
<?php
$arr=array('Hello','world');//(0=>Hello,1=>world)
echo $arr[2];
?>
error: Undefined offset 2
It means you're referring to an array key that doesn't exist. "Offset"
refers to the integer key of a numeric array, and "index" refers to the
string key of an associative array.
Undefined offset means there's an empty array key for example:
$a = array('Felix','Jon','Java');
// This will result in an "Undefined offset" because the size of the array
// is three (3), thus, 0,1,2 without 3
echo $a[3];
You can solve the problem using a loop (while):
$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
// Increase count by 1, thus, $i=1
$i++;
$groupname[$i] = base64_decode(base64_decode($row['groupname']));
// Set the first position of the array to null or empty
$groupname[0] = "";
}

explode single variable in php

Here is what i have in php :
I need to do explode the given variable
$a = "hello~world";
I need to explode as
$first = "hello";
$second = "world";
How can i do this ??
Here is what i have tried so far.
<?php
$str = "a~b";
$a = (explode("~",$str));
$b = (explode("~",$str));
echo explode('.', 'a.b');
?>
I know i did wrong. What is my mistake and how can i fix this ?
If you know the number of variables you're expecting to get back (ie. 2 in this case) you can just assign them directly into a list:
list($first, $second) = explode('~', $a);
// $first = 'hello';
// $second = 'world';
Explode function will return an array with "explosed" elements
So change your code as follows (if you know that only two elements will be present)
list($a, $b) = explode('~', $str);
//You don't need to call explode one time for element.
Otherwise, if you don't know the number of elements:
$exploded_array = explode('~', $str);
foreach ($exploded_array as $element)
{
echo $element;
}
explode returns an array. explode will break the given string in to parts using given character(here its ~) and will return an array with the exploded parts.
$a = "hello~world";
$str_array = explode("~",$a);
$first = $str_array[0];
$second = $str_array[1];
echo $first." ".$second;
Your code should trigger a clear error message with debug information:
Notice: Array to string conversion
... on this line:
echo explode('.', 'a.b');
... and finally print this:
Array
I suppose you would not ignore this helpful information if you'd seen it so you've probably haven't configured your PHP development box to display error messages. The simplest way is, when installing PHP, to get your php.ini file by copying php.ini-development instead of php.ini-production. If you are using a third-party build, just tweak the error_reporting and display_errors directives.
As about the error, you have to understand that arrays are complex data structures, not scalar values. You cannot print an array as-is with echo. In the development phase you can inspect it with var_dump() (like any other variable).

Undefined offset 1

I am facing a problem that undefined offset :1 in line 3. I can't understand that what type of error it is.
Can anyone tell me that why such error occurs in php
Undefined offset in line : 3
foreach ($lines as $line)
{
list($var,$value) = explode('=', $line); //line 3
$data[$var] = $value;
}
Your are getting PHP notice because you are trying to access an array index which is not set.
list($var,$value) = explode('=', $line);
The above line explodes the string $line with = and assign 0th value in $var and 1st value in $value. The issue arises when $line contains some string without =.
I know this an old question and the answer provided is sufficient.
Your are getting PHP notice because you are trying to access an array
index which is not set.
But I believe the best way to overcome the problem with undefined indexes when there are cases where you may have an empty array using the list()/explode() combo is to set default values using array_pad().
The reason being is when you use list() you know the number of variables you want from the array.
For example:
$delim = '=';
$aArray = array()
$intNumberOfListItems = 2;
list($value1, $value2) = array_pad(explode($delim, $aArray, $intNumberOfListItems ), $intNumberOfListItems , null);
Essentially you pass a third parameter to explode stating how many values you need for your list() variables (in the above example two). Then you use array_pad() to give a default value (in the above example null) when the array does not contain a value for the list variable.
This is caused because your $line doesn't contain "=" anywhere in the string so it contains only one element in array.list() is used to assign a list of variables in one operation. Your list contains 2 elements but as from data returned by implode, there is only one data. So it throws a notice.
A way to overcome that is to use array_pad() method.
list($var,$value) = array_pad(explode('=', $line),2,null);
by doing list($var, $value) php will expect an array of 2 elements, if the explode function doesn't find an equal symbol it will only return an array with 1 element causing the undefined offset error, offset 1 is the second element of an array so most likely one of your $line variables doesn't have an equal sign
This is due to the array. The array index is not showing due to this undefine offset error will come...
So please check the array with print_r function.
The list language construct is used to create individual variables from an array. If your array doesn't have enough elements for the number of variables you are expecting in the list call, you will get an error. In your case you have 2 variables so you need an array with 2 items - indexes 0 and 1.
http://php.net/manual/en/function.list.php
Solution:
$lines = array('one' => 'fruit=apple', 'two' => 'color=red', 'three' => 'language');
foreach ($lines as $line)
{
list($var,$value) = (strstr($line, '=') ? explode('=', $line) : array($line, ''));
$data[$var] = $value;
}
print_r($data);
Try this one..
For reference
http://in1.php.net/manual/en/function.list.php
http://in1.php.net/manual/en/function.explode.php

undefined offset PHP error

I am receiving the following error in PHP
Notice undefined offset 1: in C:\wamp\www\includes\imdbgrabber.php line 36
Here is the PHP code that causes it:
<?php
# ...
function get_match($regex, $content)
{
preg_match($regex,$content,$matches);
return $matches[1]; // ERROR HAPPENS HERE
}
What does the error mean?
If preg_match did not find a match, $matches is an empty array. So you should check if preg_match found an match before accessing $matches[0], for example:
function get_match($regex,$content)
{
if (preg_match($regex,$content,$matches)) {
return $matches[0];
} else {
return null;
}
}
How to reproduce this error in PHP:
Create an empty array and ask for the value given a key like this:
php> $foobar = array();
php> echo gettype($foobar);
array
php> echo $foobar[0];
PHP Notice: Undefined offset: 0 in
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) :
eval()'d code on line 1
What happened?
You asked an array to give you the value given a key that it does not contain. It will give you the value NULL then put the above error in the errorlog.
It looked for your key in the array, and found undefined.
How to make the error not happen?
Ask if the key exists first before you go asking for its value.
php> echo array_key_exists(0, $foobar) == false;
1
If the key exists, then get the value, if it doesn't exist, no need to query for its value.
Undefined offset error in PHP is Like 'ArrayIndexOutOfBoundException' in Java.
example:
<?php
$arr=array('Hello','world');//(0=>Hello,1=>world)
echo $arr[2];
?>
error: Undefined offset 2
It means you're referring to an array key that doesn't exist. "Offset"
refers to the integer key of a numeric array, and "index" refers to the
string key of an associative array.
Undefined offset means there's an empty array key for example:
$a = array('Felix','Jon','Java');
// This will result in an "Undefined offset" because the size of the array
// is three (3), thus, 0,1,2 without 3
echo $a[3];
You can solve the problem using a loop (while):
$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
// Increase count by 1, thus, $i=1
$i++;
$groupname[$i] = base64_decode(base64_decode($row['groupname']));
// Set the first position of the array to null or empty
$groupname[0] = "";
}

Categories