Get the first element of the array

I have an array:

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

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

One requirement: it cannot be done by reference passing, so array "shift" is not a good solution.

How can I do that?

#1 building

Use:

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

By default, array? Slice does not hold the key, so we can safely use zero as the index.

#2 building

You can use the language construction "list" to get the nth element:

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

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

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

You can perform the same operation on the key using the array? Keys function:

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

#3 building

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

#4 building

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

Output:

apple

#5 building

There are two solutions for you.

Solution 1 - just use the key. You didn't say you couldn't 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]];

Tags: PHP

Posted on Fri, 13 Dec 2019 06:35:55 -0800 by altaergo