YoYo YoYo - 1 year ago 80
PHP Question

Undefined offset error in array when count show the number of element inside

As stated in the title, I encounter a strange problem for the following code.

for($i=0; $i < count($maindata) ; $i++){
$currentId = $maindata[$i]['SubmissionId'];
$output = array_filter($subdata, function ($value) use ($currentId)
{ return $subdata['ParentId'] == $currentId; });

echo 'total sub data '.count($output); //output 86

for($j=0; $j < count($output) ; $j++){
echo $output[$j]['SubmissionId']; //Undefined offset Error

As you can see, I loop through an array. Inside the loop I filter out another array to get the associate data.

And then I echo the count of the filter array and echo the data with another loop. The code was fine for first item and it show data but starting from the second item, it show

Notice: Undefined offset: 0 in myfile on line 79

inside the second loop but the count still showing correct answer also. line 79 is
echo $output[$j]['SubmissionId']; //Undefined offset Error

Please help me to figure out what is the problem. Thanks in advance.

Answer Source


Inside second iteration use this:-

if(isset($output[$j]['SubmissionId'])){echo $output[$j]['SubmissionId'];}


$output is a filtered sub-array and due to filtration it's quite possible that some indexes are missing

when you did for($j=0; $j < count($output) ; $j++){ and if count($output) is 86 means loop will go for 0-85 (in sequential order)

Now if $output has missed index 3 (for example) then the code $output[$j]['SubmissionId'] will give error

So check that using above code and problem is solved.

2nd opinion:-

you can do like below:-

$output = array_values($output);
echo 'total sub data '.count($output); //output 86

for($j=0; $j < count($output) ; $j++){
 echo $output[$j]['SubmissionId'];

Note:- this approach will re-index your array and if some-where you are going to use original indexes then this code will lead you to problems.

3rd option(better than 2nd one)

Since foreach() take care of indexes so instead of for() loop use foreach.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download