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-
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With