suhaskunte777's avatar

Undefined offset: 0 in foreach loop

I am gettting issue in foreach loop where i am converting data into array. dd my all data is recieving but in forloop it not working. I am using Laravel 5.7

    "php": "^7.1.3",
    "barryvdh/laravel-debugbar": "^3.2",
    "fideloper/proxy": "^4.0",
    "laravel/framework": "5.7.*",
    "laravel/tinker": "^1.0",
    "laravelcollective/html": "^5.7",
    "sven/artisan-view": "^3.1",
    "way/generators": "^3.0"

hear is my code in controller '''

$node = Qnode::select('id', 'main_id')->with('datas')->get()->toArray(); foreach ($node as $item) {

//this code give me right result 
dd($item['datas'][0]['pivot']['qanswer_id']);

//but here i am getting Undefined Offset:0
        $data[$item['id']] = ['main_id' => $item['main_id'], 'data_id' => $item['datas'][0]['pivot']['qanswer_id']];
    }
    Auth::user()->qnodes()->sync($data);

'''

0 likes
5 replies
goatshark's avatar

@suhaskunte777 In the event that a Qnode does not have a Data, $item['datas'] will be empty, so no [0]. You could throw in a check to see if there's anything in $item['data'] before referencing $item['data'][0], or just get right to the point and check for the existence of $item['data'][0] itself.

suhaskunte777's avatar

Thanks to reply @goatshark I tried again. It working and giving me data when i do dd() in same foreach loop but when i tried without dd() it not working. I also worked on such array in Laravel 5.6 and last month 5.7, their it working properly.

Cronix's avatar
Cronix
Best Answer
Level 67
$item['datas']

That's an array, which may or may not always have values since it's a relationship. You're assuming it always will.

Try checking the output of this

foreach ($node as $item) {
    dump($item['datas']); // does every $item contain an array of datas with values?
}

The reason why it's working with dd(), is because dd() kills the loop cycle. It's not iterating through the whole array. It iterates once until it hits the dd() and then stops. So maybe the first one has it and it outputs fine, but maybe on the 2nd iteration there is no element at position 0 in the array.

What you need to figure out is what data_id should be if $item['datas'][0]['pivot']['qanswer_id'] doesn't exist for each item.

1 like
suhaskunte777's avatar

Thanks for Help. I made mistake in understanding data. Actually I am getting another set of array in my $item['datas'] it need another foreach loop to access it.

print_r($item['datas']);

And it gives me following result. Array ( [0] => Array ( [id] => 2 [pivot] => Array ( [qnode_id] => 1 [qanswer_id] => 2 ) ) ) 0

now with foreach($item['datas'] as value) { print_r($value['id']); }

getting desired result.

suhaskunte777's avatar

@Cronix as per your advise i search my whole array and i get empty $item['datas'] thats where it showing error. Thanks .....

Please or to participate in this conversation.