獲取數組的第一個元素

我有一個數組: php

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

我想得到此數組的第一個元素。 apple 預期結果: apple 安全

一個要求: 它不能經過引用傳遞來完成 ,因此array_shift不是一個好的解決方案。 app

我怎樣才能作到這一點? 函數


#1樓

採用: this

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

默認狀況下, array_slice不保留鍵,所以咱們能夠安全地使用零做爲索引。 spa


#2樓

您能夠使用語言構造「列表」得到第N個元素: code

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

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

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

使用array_keys函數,您能夠對鍵執行相同的操做: 索引

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

#3樓

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

#4樓

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

輸出: ip

apple

#5樓

爲您提供兩種解決方案。

解決方案1-只需使用鑰匙。 您沒有說不能使用它。 :)

<?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. */');
?>

解決方案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. */');
?>

解決方案3-array_keys()

echo $array[array_keys($array)[0]];
相關文章
相關標籤/搜索