Wednesday, June 6, 2012

PHP(array with shift, unshift, pop, puch functions)


<?php
$numbers = array(1,2,3,4,5,6);
print_r($numbers);
echo "<br /> <br />";

//shifts first element out of an array
//and returns it.
$a = array_shift($numbers);
echo "a: ". $a. "<br/>";
print_r($numbers);
echo "<br /> <br />";

//prepends an element to an array
//returns the element count.
$b = array_unshift($numbers, 'first');
echo "b: " . $b . "<br />";
print_r($numbers);
echo "<br /> <br />";

echo "<hr/>";

//pops an element out of an array
//and returns it.
$c = array_pop($numbers);
echo "c: " . $c . "<br />";
print_r($numbers);
echo "<br /><br />";


//pushes the element onto the end of an array,
//returns the element count.
$d  = array_push($numbers, "last");
echo "d:" . $d ."<br />";
print_r($numbers);
echo "<br /> <br />";

?>


//RESULT ON BROWSER
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )

a: 1
Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 )

b: 6
Array ( [0] => first [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 ) 


c: 6
Array ( [0] => first [1] => 2 [2] => 3 [3] => 4 [4] => 5 )

d:6
Array ( [0] => first [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => last ) 

No comments:

Post a Comment