Get the first element of an array

后端 未结 30 2110
醉酒成梦
醉酒成梦 2020-11-22 10:59

I have an array:

array( 4 => \'apple\', 7 => \'orange\', 13 => \'plum\' )

I would like to get the first element of this array. Expect

相关标签:
30条回答
  • 2020-11-22 11:28
    $myArray = array (4 => 'apple', 7 => 'orange', 13 => 'plum');
    $arrayKeys = array_keys($myArray);
    
    // The first element of your array is:
    echo $myArray[$arrayKeys[0]];
    
    0 讨论(0)
  • 2020-11-22 11:28

    Two solutions for you.

    Solution 1 - Just use the key. You have not said that you can not use it. :)

    <?php
        // Get the first element of this array.
        $array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
    
        // Gets the first element by key
        $result = $array[4];
    
        // Expected result: string apple
        assert('$result === "apple" /* Expected result: string apple. */');
    ?>
    

    Solution 2 - array_flip() + key()

    <?php
        // Get first element of this array. Expected result: string apple
        $array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
    
        // Turn values to keys
        $array = array_flip($array);
    
        // You might thrown a reset in just to make sure
        // that the array pointer is at the first element.
        // Also, reset returns the first element.
        // reset($myArray);
    
        // Return the first key
        $firstKey = key($array);
    
        assert('$firstKey === "apple" /* Expected result: string apple. */');
    ?>
    

    Solution 3 - array_keys()

    echo $array[array_keys($array)[0]];
    
    0 讨论(0)
  • 2020-11-22 11:31

    A kludgy way is:

    $foo = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
    
    function get_first ($foo) {
        foreach ($foo as $k=>$v){
            return $v;
        }
    }
    
    print get_first($foo);
    
    0 讨论(0)
  • I don't like fiddling with the array's internal pointer, but it's also inefficient to build a second array with array_keys() or array_values(), so I usually define this:

    function array_first(array $f) {
        foreach ($f as $v) {
            return $v;
        }
        throw new Exception('array was empty');
    }
    
    0 讨论(0)
  • 2020-11-22 11:33

    current($array) can get you the first element of an array, according to the PHP manual.

    Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array.

    So it works until you have re-positioned the array pointer, and otherwise you'll have to reset the array using reset()

    0 讨论(0)
  • 2020-11-22 11:34

    No one has suggested using the ArrayIterator class:

    $array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
    $first_element = (new ArrayIterator($array))->current();
    echo $first_element; //'apple'
    

    gets around the by reference stipulation of the OP.

    0 讨论(0)
提交回复
热议问题