在PHP中返回关联数组的第一个键 [英] Return first key of associative array in PHP

查看:357
本文介绍了在PHP中返回关联数组的第一个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获取关联数组的第一个键,而不通过array_keys()等创建临时变量以通过引用传递.不幸的是,reset()array_shift()都通过引用接受了数组参数,因此似乎都不可行.

I'm trying to obtain the first key of an associative array, without creating a temporary variable via array_keys() or the like, to pass by reference. Unfortunately both reset() and array_shift() take the array argument by reference, so neither seem to be viable results.

使用PHP 5.4,我将上天堂; array_keys($array)[0];,但不幸的是,这当然也不是一种选择.

With PHP 5.4 I'll be in heaven; array_keys($array)[0];, but unfortunately this of course is not an option either.

我可以创建一个函数来实现此目的,但是我只能想象PHP的array_*函数有某种组合,它们会在单个语句中产生所需的结果,我无法认为或提出来.

I could create a function to serve the purpose, but I can only imagine there is some concoction of PHP's array_* functions that will produce the desired result in a single statement, that I cannot think of or come up with.

所以:

$array = array('foo' => 'bar', 'hello' => 'world');

$firstKey = assorted_functions($array); // $firstKey = 'foo'

在我的问题中使用无引用"子句的原因仅是因为我认为将需要array_keys()(如果有通过引用传递的方式,请开火)

The reason for the "no reference" clause in my question is only for the fact that I assume array_keys() will be required (if there is a way passing by reference, please fire away)

我会使用key(),但这需要一个reset(),因为我不确定在执行此操作时指针将在哪里.

I'd use key(), but that requires a reset() as I'm not sure where the pointer will be at the time of this operation.

附录

我正在跟进我最近的一个认识:正如我在评论中提到的那样,它将完全使用内存,因此,如果这是一个问题,那么这个问题就没有解决办法了.

I'm following up on a realization I had recently: as I mentioned in the comments, it'll use the memory all the same, so if that's a concern, this question hath no solution.

$a = range(0,99999);
var_dump(memory_get_peak_usage()); // int(8644416)
$k = array_keys($a)[0];
var_dump(memory_get_peak_usage()); // int(17168824)

知道这一点,因为PHP没有这种优化功能,但是认为它值得明确提及.

I knew this, as PHP doesn't have such optimization capabilities, but figured it warranted explicit mention.

被接受的答案的简短性很好,但是,如果您正在使用合理大小的数组,它将可以正常工作.

The brevity of the accepted answer is nice though, and'll work if you're working with reasonably sized arrays.

推荐答案

尽管array_shift(array_keys($array));可以工作,但是current(array_keys($array));更快,因为它不推进内部指针.

Although array_shift(array_keys($array)); will work, current(array_keys($array)); is faster as it doesn't advance the internal pointer.

但是任何一个都可以工作.

Either one will work though.

正如@TomcatExodus指出的那样,array_shift();期望通过引用传递一个数组,因此第一个示例将发出错误.最好坚持使用current();

As @TomcatExodus noted, array_shift(); expects an array passed by reference, so the first example will issue an error. Best to stick with current();

这篇关于在PHP中返回关联数组的第一个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆