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

查看:39
本文介绍了在 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.

任一个都行.

正如@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天全站免登陆