我有一个数组:

阵列(4 = > '苹果',7 = >“橙色”,13 = >“李子”)

我想要得到这个数组的第一个元素。预期结果:串苹果

一个要求:它不能通过引用传递来完成,所以array_shift不是一个好的解决方案。

我该怎么做呢?


当前回答

<?php
    $arr = array(3 => "Apple", 5 => "Ball", 11 => "Cat");
    echo array_values($arr)[0]; // Outputs: Apple
?>

其他的例子:

<?php
    $arr = array(3 => "Apple", 5 => "Ball", 11 => "Cat");
    echo current($arr); // Outputs: Apple
    echo reset($arr); // Outputs: Apple
    echo next($arr); // Outputs: Ball
    echo current($arr); // Outputs: Ball
    echo reset($arr); // Outputs: Apple
?>

其他回答

有两个解决方案。

解决方案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]];

对Sarfraz发布的内容做了一个小改动:

$array = array(1, 2, 3, 4, 5);
$output = array_slice($array, 0, 1);
print_r ($output);

PHP 7.3添加了两个函数,用于直接获取数组的第一个和最后一个键,而无需修改原始数组,也无需创建任何临时对象:

array_key_first array_key_last

除了语义上有意义外,这些函数甚至不移动数组指针(就像foreach那样)。

有了键,就可以直接通过键获取值。


示例(它们都需要PHP 7.3+)

获取第一个/最后一个键和值:

$my_array = ['IT', 'rules', 'the', 'world'];

$first_key = array_key_first($my_array);
$first_value = $my_array[$first_key];

$last_key = array_key_last($my_array);
$last_value = $my_array[$last_key];

获取第一个/最后一个值为一行,假设数组不能为空:

$first_value = $my_array[ array_key_first($my_array) ];

$last_value = $my_array[ array_key_last($my_array) ];

获取第一个/最后一个值为一行程序,默认为空数组:

$first_value = empty($my_array) ? 'default' : $my_array[ array_key_first($my_array) ];

$last_value = empty($my_array) ? 'default' : $my_array[ array_key_last($my_array) ];

Use:

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

默认情况下,array_slice不保留键,所以我们可以安全地使用0作为索引。

这有点晚了,但我遇到了一个问题,我的数组包含数组元素作为其子元素,因此我不能获得第一个数组元素的字符串表示形式。通过使用PHP的current()函数,我管理了这个:

<?php
    $original = array(4 => array('one', 'two'), 7 => array('three', 'four'));
    reset($original);  // to reset the internal array pointer...
    $first_element = current($original);  // get the current element...
?>

感谢所有当前的解决方案帮助我得到这个答案,我希望这能帮助到别人!