Home PHP How to remove the first element of an array using PHP and then storing the element in a variable?
 
 
 

How to remove the first element of an array using PHP and then storing the element in a variable?

PDF Print E-mail

Question: How to remove the first element of an array using PHP and then storing the element into a variable?

 

Answer:

  • By using the PHP function 'array_shift' we can remove the first value of an array
    • array_shift - Shift an element off the beginning of array (PHP 4 & 5)


Example:

 

$array = array("apple","peach","pineapple","banana");
$first_element = array_shift($array);


echo '<pre>';
print_r($array);
echo '</pre>';

echo $first_element;



In the above example we have an array with 4 values, now using the 'array_shift' function we remove the first value namely apple and store it in the $first_element variable.

 

Now if we print the contents of $array we'll notice there are only 3 values left namely peach, pineapple and banana and apple belongs to the $first_element variable.

 

Output from example:


//Contents of $array
Array
(
    [0] => peach
    [1] => pineapple
    [2] => banana
)

//Value of First Element
apple

+/-
+/- Write comment
Your Contact Details:
Comment:
[b] [i] [u] [url] [quote] [code] [img]   
:angry::0:confused::cheer:B):evil::silly::dry::lol::kiss::D:pinch:
:(:shock::X:side::):P:unsure::woohoo::huh::whistle:;):s
:!::?::idea::arrow:
Security Please input the anti-spam code that you can read in the image.
 
 
Banner