开发者

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

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 ind开发者_运维知识库ex? 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().


You can do it this way:

$keys = array_keys($_GET);

echo "First item = " . $_GET[$keys[0]];


Nope, it is not possible.

Try this:

file.php?foo=bar

file.php contents:

<?php

print_r($_GET);

?>

You get

Array
(
    [foo] => bar
)

If you want to access the element at 0, try file.php?0=foobar.

You can also use a foreach or for loop and simply break after the first element (or whatever element you happen to want to reach):

foreach($_GET as $value){
    echo($value);
    break;
}


Nope -- they are mapped by key value pairs. You can iterate the they KV pair into an indexed array though:

foreach($_GET as $key => $value) {
    $getArray[] = $value;
} 

You can now access the values by index within $getArray.


As another weird workaround, you can access the very first element using:

 print $_GET[key($_GET)];

This utilizes the internal array pointer, like reset/end/current(), could be useful in an each() loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜