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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With