Steven
Steven

Reputation: 19435

Why do I get 'Undefined offset: 0'?

I'm develop a website and it looks fine. Then I turned on debugging to see if I had any errors, and I get this message:

Notice: Undefined offset: 0 in I:\path\to\file\MyFile.class.php on line 105

On that line you will find the following code:

$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result[0]; // line 105

If I do a print_r(result) I get the following result:

Array (
    [0] => Array (
        [id] => 3721
        [parentID] =>
    )
)
Array (
) 

As you can see the result contains twoarrays. The first one has data, the second one has no data. I've never seen print_r output two arrays like this. I'm guessing it's the second one causing me the problems.

Can anyone advice me of why that second array sneaks in?

VAR dump

array
  0 => 
    array
      'id' => string '3721' (length=4)
      'parentID' => null
array
  empty

Upvotes: 0

Views: 1737

Answers (1)

Karoly Horvath
Karoly Horvath

Reputation: 96266

You fetch all records matching the query. If there are no records it will return an empty array. Obviously there is no 0 element in an empty array.

Upvotes: 5

Related Questions