來源:百度SEO公司
我有一個數組:
array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )
我想獲得此數組的第一個元素。 apple
預期結果: apple
一個要求: 它不能通過引用傳遞來完成 ,所以array_shift
不是一個好的解決方案。
我怎樣才能做到這一點?
#1樓
采用:
$first = array_slice($array, 0, 1); $val= $first[0];
默認情況下, array_slice
不保留鍵,因此我們可以安全地使用零作為索引。
#2樓
您可以使用語言構造“列表”獲得第N個元素:
// 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;
輸出:
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]];