我有一个数组:

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

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

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

我该怎么做呢?


当前回答

一种简单的方法是:

$foo = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );

function get_first ($foo) {
    foreach ($foo as $k=>$v){
        return $v;
    }
}

print get_first($foo);

其他回答

有两个解决方案。

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

当前数组($)

根据PHP手册,返回数组的第一个元素。

每个数组都有一个指向其“当前”元素的内部指针,该指针被初始化为插入数组的第一个元素。

所以它一直工作,直到你重新定位数组指针,否则你将不得不使用reset(),它将倒带数组并返回数组的第一个元素

根据PHP手动复位。

Reset()将数组的内部指针倒回到第一个元素,并返回第一个数组元素的值。

current()和reset()的示例

$array = array('step one', 'step two', 'step three', 'step four');

// by default, the pointer is on the first element
echo current($array) . "<br />\n"; // "step one"

//Forward the array pointer and then reset it

// skip two steps
next($array);
next($array);
echo current($array) . "<br />\n"; // "step three"

// reset pointer, start again on step one
echo reset($array) . "<br />\n"; // "step one"

你可以通过下面的代码获取第一个元素:

$array_key_set = array_keys($array);
$first_element = $array[$array_key_set[0]];

或者使用:

$i=0;
foreach($array as $arr)
{
  if($i==0)
  {
    $first_element=$arr;
    break;
  }
 $i++;
}
echo $first_element;

Use:

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

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

我认为使用array_values是最好的选择。你可以从函数的结果中返回下标0处的值,得到'apple'。