Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays: array_shift($arr) or $arr[0]?

Tags:

arrays

php

Which one would you use?

Basically I only want to get the 1st element from a array, that's it.

like image 954
xxBarbieGirlxx Avatar asked Jun 29 '11 20:06

xxBarbieGirlxx


People also ask

What is the use of array_shift () function?

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).

Do PHP arrays start at 0 or 1?

PHP lets you create 2 types of array: Indexed arrays have numeric indices. Typically the indices in an indexed array start from zero, so the first element has an index of 0 , the second has an index of 1 , and so on.

What is first index value of an array?

JavaScript arrays are zero-indexed: the first element of an array is at index 0 , the second is at index 1 , and so on — and the last element is at the value of the array's length property minus 1 .

How do I remove the first key from an array?

To remove the first element or value from an array, array_shift() function is used. This function also returns the removed element of the array and returns NULL if the array is empty.


1 Answers

Well, they do different things.

  • array_shift($arr) takes the first element out of the array, and gives it to you.

  • $arr[0] just gives it to you... if the array has numeric keys.

An alternative that works for associative arrays too is reset($arr). This does move the array's internal pointer, but unless you're using those functions this is unlikely to affect you.

like image 107
Lightness Races in Orbit Avatar answered Nov 01 '22 13:11

Lightness Races in Orbit