Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can items in PHP associative arrays not be accessed numerically (i.e. by index)?

Tags:

arrays

php

I'm trying to understand why, on my page with a query string, the code:

echo "Item count = " . count($_GET);
echo "First item = " . $_GET[0];

Results in:

Item count = 3 First item =

Are PHP associative arrays distinct from numeric arrays, so that their items cannot be accessed by index? Thanks-

like image 671
Yarin Avatar asked Dec 27 '22 21:12

Yarin


2 Answers

They can not. When you subscript a value by its key/index, it must match exactly.

If you really wanted to use numeric keys, you could use array_values() on $_GET, but you will lose all the information about the keys. You could also use array_keys() to get the keys with numerical indexes.

Alternatively, as Phil mentions, you can reset() the internal pointer to get the first. You can also get the last with end(). You can also pop or shift with array_pop() and array_shift(), both which will return the value once the array is modified.

like image 157
alex Avatar answered Dec 30 '22 09:12

alex


Yes, the key of an array element is either an integer (must not be starting with 0) or an associative key, not both.

You can access the items either with a loop like this:

foreach ($_GET as $key => $value) {
}

Or get the values as an numerical array starting with key 0 with the array_values() function or get the first value with reset().

like image 36
Berdir Avatar answered Dec 30 '22 09:12

Berdir