Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw away whole array but the first item

Tags:

php

Assume I have the following array:

$array(
  '32' => array('name' => 'paul', 'age' => 43),
  '17' => array('name' => 'eric', 'age' => 19),
  '99' => array('name' => 'dave', 'age' => 65)
)

I am only interested in the first $array item:

$array2 = array('key'=> 32, 'name' => 'paul', 'age' => 43)

What is the most efficient way to accomplish this? In other words, can I throw out all other items of $array with one command?

like image 656
Jan Willem Avatar asked Dec 21 '25 11:12

Jan Willem


1 Answers

Use array_shift().

array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.

$array2 = array_shift($array);

This means that $array2 now holds the first element, while $array holds the rest of the elements.

like image 136
Madara's Ghost Avatar answered Dec 23 '25 01:12

Madara's Ghost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!