我有一个数组:

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

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

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

我该怎么做呢?


当前回答

保持简单!这里有很多正确答案,但为了尽量减少所有的混乱,这两个方法有效,并减少了大量的开销:

Key ($array)获取数组的第一个键 Current ($array)获取数组的第一个值

编辑: 关于下面的评论。以下示例将输出string(13)“PHP代码测试”

$array = array
(
   '1'           => 'PHP code test',  
   'foo'         => 'bar', 5 , 5 => 89009, 
   'case'        => 'Random Stuff: '.rand(100,999),
   'PHP Version' => phpversion(),
   0             => 'ending text here'
);

var_dump(current($array));

其他回答

大部分都有用!但是对于一个快速的单线(低资源)呼叫:

$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
echo $array[key($array)];

// key($array) -> will return the first key (which is 4 in this example)

虽然这是可行的,而且还不错,但请参阅我的额外答案: https://stackoverflow.com/a/48410351/1804013

当前数组($)

根据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"

同样值得记住的是您执行此操作的上下文,因为详尽的检查可能是昂贵的,而且并不总是必要的。

例如,这个解决方案在我使用它的情况下工作得很好(但显然不能在所有情况下都依赖它……)

 /**
 * A quick and dirty way to determine whether the passed in array is associative or not, assuming that either:<br/>
 * <br/>
 * 1) All the keys are strings - i.e. associative<br/>
 * or<br/>
 * 2) All the keys are numeric - i.e. not associative<br/>
 *
 * @param array $objects
 * @return boolean
 */
private function isAssociativeArray(array $objects)
{
    // This isn't true in the general case, but it's a close enough (and quick) approximation for the context in
    // which we're using it.

    reset($objects);
    return count($objects) > 0 && is_string(key($objects));
}

一行闭行,复制,重置:

<?php

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

echo (function() use ($fruits) { return reset($fruits); })();

输出:

apple

或者更短的短箭头函数:

echo (fn() => reset($fruits))();

这使用如上所述的按值变量绑定。两者都不会改变原来的指针。

一种简单的方法是:

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

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

print get_first($foo);