How to easily obtain the key-value pairs of the first and last elements of an array?

Source: Internet
Author: User
Current practice: {code...} is there a simple method? Current practice:

# Join array $ a = ['A' => 1 ,... 'B' => 2]; $ first = reset ($ a); $ first_key = key ($ a); $ last = end ($ ); $ last_key = key ($ B );

Is there a simple way?

Reply content:

Current practice:

# Join array $ a = ['A' => 1 ,... 'B' => 2]; $ first = reset ($ a); $ first_key = key ($ a); $ last = end ($ ); $ last_key = key ($ B );

Is there a simple way?

If you obtain the key and value respectively, the topic can also obtain the fisrt method simply:

$first = reset($a);

If you want to obtain both the key and value at once, you can use each:

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

Ps: Unfortunately, PHP does not support comma expressions. Otherwise, you can directly write it like this:

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

Supplement: the list can be nested, so you can also write it like this:

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

phpprint_r(current(array_keys($a)));//aprint_r(current(array_values($a)));//1print_r(end(array_keys($a)));//bprint_r(end(array_values($a)));//2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.