Why am I throw an error for undefined index when I'm checking whether it's empty?

247 Views Asked by At

I've got the following error:

ErrorException: Undefined array key 0 in /Users/User/Sites/Site/app/Jobs/MigrateData.php:67

This is correct in the one instance for my Job, the $this->schools is an empty array and therefore shouldn't be hitting the create. Sorry, I'm a little unsure why this is throwing an error.

    $this->data = [];

    $i=0;
    foreach($core_data as $core) {

        $dataCode = DataCode::where('code', $core->code)->first();

        if ($dataCode instanceof DataCode) {
            $this->data[$i]['data_id'] = $dataCode->id;
            $this->data[$i]['data_name'] = $dataCode->name;
        }

        $i++;
    }

    if (!empty($this->data)) {
        $data = Data::create([
            'first_name' => $this->data[0]['data_name']
        ]);
    }

Any help as to where I am going wrong?

1

There are 1 best solutions below

0
RiggsFolly On

Load the array like this, it will add a new occurance by using the [] and then add an array to that new occurance

$this->data[] = ['data_id'   => $dataCode->id,
                 'data_name' => $dataCode->name];