katie hudson
katie hudson

Reputation: 2893

Undefined index in array element

seem to be experiencing something strange. I am loading an Excel file's data into an array. I am handling things like so

foreach ($data->toArray() as $value) {
    dd($value);
    if(!empty($value)){
        foreach ($value as $v) {
            dd($v['id']);
            $insert[] = [
                'id' => $v['id'],
                'name' => $v['name']
            ];
        }
    }
}

Now the first dd() (laravel output) produces something like so

array:809 [▼
  0 => array:20 [▼
    "id" => "123"
    "name" => "something"
  ]
  ...

So I can see there is an array element called id. The second dd, which calls this array element, produces the output 123

The problem comes where I am filling the array with this data. Although I am still using $v['id'] which works for the output, within the array I get the error

Undefined index: id

Why would this be the case when the index is there?

Thanks

Upvotes: 3

Views: 5609

Answers (1)

Laerte
Laerte

Reputation: 7083

Try to add an if to check if the keys really exist in your array. This will avoid situations when the key does not exist and the Undefined index: id error appear.

foreach ($data->toArray() as $value) {
    if(!empty($value)){
        foreach ($value as $v) {
            if (array_key_exists("id",$v) &&
                array_key_exists("name",$v)) {
                $insert[] = [
                    'id' => $v['id'],
                    'name' => $v['name']
                ];
            }
        }
    }
}

Upvotes: 2

Related Questions