Undefined PHP error offset, attempt to read from file

I get the PHP "Undefined offset" error and don’t understand what causes it. I'm just a beginner.

Notice: Undefined offset: 3 on line 58

Here is the code I'm using:

$file = fopen("portfolio.file", "r") or die("Unable to open a portfolio file.");
$portfolioFull = fread($file,filesize("portfolio.file"));
fclose($file);
$portfolioItems = explode(";", $portfolioFull);
$i = count($portfolioItems);
echo $i;
while ($i >= 0){
    $portfolio[$i] = explode("||", $portfolioItems[$i]);
    $i = $i - 1;
}
echo $portfolio[1][0];
echo $portfolio[1][1];
echo $portfolio[1][2];
echo $portfolio[2][0];
echo $portfolio[2][1];
echo $portfolio[2][2];

Here is the portfolio file that contains:

Item 1 Title
||
Item 1 Description
||
DOWNLOAD PENDING
;
Item 2 Title
||
Item 2 Description
||
DOWNLOAD UNAVAILABLE
;
Test Item
||
Test Description
||
DOWNLOAD AVAILABLE

And here is what the debug echo says: https://gyazo.com/2e1a6e90f1a33578b40e5f330e19dd78

Any clues on how to fix this?

+4
source share
1 answer
$i = count($portfolioItems);
echo $i;
$i-- ; //reduce by one should fix the problem
while ($i >= 0){
    $portfolio[$i] = explode("||", $portfolioItems[$i]);
    $i = $i - 1;
}

Since the index of the array starts from zero, the value of the last element will be count($array) -1.

In this case, you use the count value, which will be 1 more than the last index. Example: if the array has 3 elements, the indices will be 0, 1, 2. Attempting to use 3 as an index will give you this error.

+2

Source: https://habr.com/ru/post/1608112/


All Articles