如何简便地获取数组的第一个,最后一个元素的键值对?

不言
Release: 2023-02-28 12:36:01
Original
3117 people have browsed it

当前的做法:

# 关联数组
$a = ['a' => 1, ... 'b' => 2];

$first = reset($a);
$first_key = key($a);

$last = end($a);
$last_key = key($b);
Copy after login
Copy after login

有木有简便点的方法呢?

回复内容:

当前的做法:

# 关联数组
$a = ['a' => 1, ... 'b' => 2];

$first = reset($a);
$first_key = key($a);

$last = end($a);
$last_key = key($b);
Copy after login
Copy after login

有木有简便点的方法呢?

如果分别获取key和value,题主获取fisrt的方法还可以再简单点:

$first = reset($a);
Copy after login

如果要一下子把key和value都获取出来,可以用each:

list($first_key, $first) = (reset($a) ? each($a) : each($a));
list($last_key, $last) = (end($a) ? each($a) : each($a));
Copy after login

ps: 可惜PHP不支持逗号表达式,要不然可以直接这样写:

list($first_key, $first) = (reset($a) , each($a));
list($last_key, $last) = (end($a) , each($a));
Copy after login

补充:list可以嵌套,所以也可以这样写:

list(,list($first_key, $first)) = array(reset($a) , each($a));
list(,list($last_key, $last)) = array(end($a) , each($a));
Copy after login

phpprint_r(current(array_keys($a)));//a
print_r(current(array_values($a)));//1
print_r(end(array_keys($a)));//b
print_r(end(array_values($a)));//2
Copy after login

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template