笑故挽风 2009-06-22 18:13 采纳率: 100%
浏览 338
已采纳

在一个(可能的)关联数组中获得第一个密钥?

What's the best way to determine the first key in a possibly associative array? My first thought it to just foreach the array and then immediately breaking it, like this:

foreach ($an_array as $key => $val) break;

Thus having $key contain the first key, but this seems inefficient. Does anyone have a better solution?

转载于:https://stackoverflow.com/questions/1028668/get-first-key-in-a-possibly-associative-array

  • 写回答

18条回答 默认 最新

  • 衫裤跑路 2009-06-22 18:16
    关注

    You can use reset and key:

    reset($array);
    $first_key = key($array);
    

    It's essentially the same as your initial code, but with a little less overhead, and it's more obvious what is happening.

    Just remember to call reset, or you may get any of the keys in the array. You can also use end instead of reset to get the last key.

    If you wanted the key to get the first value, reset actually returns it:

    $first_value = reset($array);
    

    There is one special case to watch out for though (so check the length of the array first):

    $arr1 = array(false);
    $arr2 = array();
    var_dump(reset($arr1) === reset($arr2)); // bool(true)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(17条)

报告相同问题?

悬赏问题

  • ¥20 steam下载游戏占用内存
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系