Get the first element of the array

Source: Baidu SEO Company

I have an array:

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

I want to get the first element of this array. apple expected outcome: apple

One requirement:  it can not be passed by reference to complete  , so array_shiftnot a good solution.

How can I do this?


#1st Floor

use:

$first = array_slice($array, 0, 1);  
$val= $first[0];

By default,  array_sliceit does not retain the key, so we can safely use zero as the index.


#2nd Floor

You can use the language constructs "List" won the first N elements:

// First item
list($firstItem) = $yourArray;

// First item from an array that is returned from a function
list($firstItem) = functionThatReturnsArray();

// Second item list( , $secondItem) = $yourArray; 

Use the array_keysfunction, you can perform the same operation on the key:

list($firstKey) = array_keys($yourArray);
list(, $secondKey) = array_keys($yourArray);

#3rd floor

$first_value = reset($array); // First element's value
$first_key = key($array); // First element's key

#4th floor

$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' ); foreach($arr as $first) break; echo $first; 

Output:

apple

#5th Floor

To provide you with two solutions.

Solution 1- Just use the key. You did not say 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]];

Guess you like

Origin www.cnblogs.com/1994jinnan/p/12037472.html