Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get and remove first element of an array in PHP

Tags:

arrays

php

get

Hi I am coding a system in which I need a function to get and remove the first element of the array. This array has numbers i.e.

0,1,2,3,4,5

how can I loop through this array and with each pass get the value and then remove that from the array so at the end of 5 rounds the array will be empty.

Thanks in advance

like image 882
André Figueira Avatar asked Jul 07 '12 02:07

André Figueira


People also ask

How do you delete the first element of an array in PHP?

The array_shift() function removes the first element from an array, and returns the value of the removed element. Note: If the keys are numeric, all elements will get new keys, starting from 0 and increases by 1 (See example below).

How do I remove the first element from an array?

shift() The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

What is Array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.

What is array shift in PHP?

The array_shift() function is used to remove the first element from an array, and returns the value of the removed element. All numerical array keys will be modified to start counting from zero while literal keys won't be touched.


1 Answers

You can use array_shift for this:

while (($num = array_shift($arr)) !== NULL) {
  // use $num
}
like image 168
Tim Cooper Avatar answered Oct 21 '22 04:10

Tim Cooper