获取数组的第一个元素

来源:百度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]];

猜你喜欢

转载自www.cnblogs.com/1994jinnan/p/12037472.html