获取数组的第一个元素

我有一个数组: 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]];
相关文章
相关标签/搜索