Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Get first and last key and value from array

Tags:

arrays

php

From a given array (eg: $_SERVER), I need to get the first and last key and value. I was trying use array_shift to get first value and key but what I get is value.

Here is the $_SERVER array:

print_r($_SERVER, true))

And I tried with:

echo array_shift($_SERVER);
like image 616
Mati Urbaniak Avatar asked Mar 03 '26 02:03

Mati Urbaniak


1 Answers

With PHP >= 7.3 you can get it fast, without modification of the array and without creating array copies:

$first_key = array_key_first($_SERVER);
$first_value = $_SERVER[$first_key];

$last_key = array_key_last($_SERVER);
$last_value = $_SERVER[$last_key];

See array_key_first and array_key_last.

like image 53
Alex Shesterov Avatar answered Mar 04 '26 18:03

Alex Shesterov