Can't access elements in PHP associative arrays numerically (i.e. by index)?

I am 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:

Number of items = 3 First item =

Are PHP associative arrays different from numeric arrays so their elements cannot be accessed by index? Thanks -

+4
source share
6 answers

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

If you really wanted to use the number keys, you can use array_values() in $_GET , but you will lose all information about the keys. You can also use array_keys() to get keys with numeric indices.

Alternatively, as Phil pointed out, you can reset() internal pointer to get the first one. You can also get the latter with end() . You can also put or change array_pop() and array_shift() , both will return a value after changing the array.

+5
source

Yes, the key to an array element is either an integer (should not start with 0) or an associative key, and not both.

You can access the elements either using a loop like this:

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

Either get the values ​​as a numeric array, starting at key 0 with the array_values() function, or get the first value with reset() .

+3
source

You can do it as follows:

 $keys = array_keys($_GET); echo "First item = " . $_GET[$keys[0]]; 
+2
source

No, It is Immpossible.

Try the following:

file.php?foo=bar

file.php Contents:

 <?php print_r($_GET); ?> 

You are getting

 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 foreach and just break after the first element (or any other element you want to reach):

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

No - they are matched by pairs of key values. You can repeat their KV pair into an indexed array:

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

Now you can access the index values ​​in $ getArray.

0
source

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

  print $_GET[key($_GET)]; 

In this case, an internal array pointer is used, for example, reset / end / current (), which can be useful in the each() loop.

0
source

All Articles