Preston
Preston

Reputation: 1059

Notice: Undefined Offset: 0

I am trying to get a value from an array, but when I use $array[0], I get a PHP notice 'Undefined Offset: 0'. However, when I use $array['id'] (should be the same as using '0', since 'id' is the first key in the array), I am able to get the value. I did a print_r and this was outputted:

Array ( 
     [id] => 1 
     [username] => test 
)

Shouldn't I be able to get the key using its index? I believe it was working earlier, but I don't know what I could have done to make it stop working. Any ideas?

Upvotes: 1

Views: 2473

Answers (2)

phihag
phihag

Reputation: 287885

$array['id'] is not the same as $array[0]. This confusion is probably related because of the term array. php's arrays aren't what you'd call an array in another language, they are maps or dictionaries.

(Oh, and even if they were not, the order of elements in a php array, a map, or a dictionary is up to the implementation, so while you'll get the id with $tmp = array_values($array); echo $tmp[0];, php is allowed to shuffle the array around).

Upvotes: 2

Michael Madsen
Michael Madsen

Reputation: 55009

No, you shouldn't be able to do this.

You might be thinking of arrays obtained from something like mysql_fetch_array, which, by default, lets you use both numeric and string indexes to get to the columns - but the reason you can do that is because the array contains both of those.

You can also use array_values to extract values from an array to essentially transform the indexes to numeric ones, but it's not the same thing, really.

Upvotes: 1

Related Questions