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

后端 未结 6 1641
清酒与你
清酒与你 2021-01-06 08:26

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

echo \"Item count = \" . count($_GET);
echo \"First item = \" . $_         


        
相关标签:
6条回答
  • 2021-01-06 08:53

    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.

    0 讨论(0)
  • 2021-01-06 08:54

    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;
    }
    
    0 讨论(0)
  • 2021-01-06 08:57

    You can do it this way:

    $keys = array_keys($_GET);
    
    echo "First item = " . $_GET[$keys[0]];
    
    0 讨论(0)
  • 2021-01-06 09:10

    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.

    0 讨论(0)
  • 2021-01-06 09:12

    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().

    0 讨论(0)
  • 2021-01-06 09:12

    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 讨论(0)
提交回复
热议问题