PHP Array functions
Passing arrays by value and reference
The difference between passing by value and passing by reference is that you when pass by value, you are passing a copy of the array. When passing by reference, you are passing a pointer i.e any changes made in the function you pass to can modify the original.
function foo($var) {
$var[1]++;
}
function bar(&$var) {
$var[1]++;
}
$a=array(5,6,7);
foo($a);
print "Passed by value:\n";
print_r($a);
bar($a);
print "Passed by reference:\n";
print_r($a);
output
Passed by value:
Array
(
[0] => 5
[1] => 6
[2] => 7
)
Passed by reference:
Array
(
[0] => 5
[1] => 7
[2] => 7
)
When passed by value, elements of $a remain unchanged. When passed by reference, the second element of $a changed. The only difference in code is the & in the function parameter.
Removing duplicates values from an array
The array_unique function removes duplicates from an array.
$aSample = array(1,1,6,6,6,8,"8");
print_r(array_unique($aSample));
output
Array ( [0] => 1 [2] => 6 [5] => 8 )
By default all values are compared as strings, thus there is no difference between 8 and "8".
print_r into a variable
print_r() prints array contents in a user-friendly format. The output of print_r() can also be stored into a variable. Just remember to pass your array into print_r() with a true flag as follows:
$a = array('pass','print_r','into','variable');
$variable = print_r($a,true);
print $variable;
output
Array
(
[0] => pass
[1] => print_r
[2] => into
[3] => variable
)
Removing a element from an array
To remove an element from an array, we use array_splice().
$arr = array("red", "green", "blue", "black");
print_r($arr);
for ($i = 0; $i < count($arr); $i++) {
if ($i == 2) {
array_splice($arr, $i, 1);
}
}
print_r($arr);
The element blue has been removed from the array.
Array
(
[0] => red
[1] => green
[2] => blue
[3] => black
)
Array
(
[0] => red
[1] => green
[2] => black
)
Push and Pop
array_push() and array_pop() functions are used to push and pop elements on a array. These functions have the following syntax:
array_push($array,$element);
$element = array_pop($array);
Lets look at the following code:
$mya = array(0 => "zero",1 => "one",2 => "two");
array_push($mya, "three");
$mya[] = "four";
print_r($mya);
This program would produce the following results. array_push() adds an element at the end of the array. The code on the last line is equivalent to a pop.
Array
(
[0] => zero
[1] => one
[2] => two
[3] => three
[4] => four
)
array_pop removes the last element from an array. Let's look at the following program:
$mya = array(0 => "zero",1 => "one",2 => "two");
$n = array_pop($mya);
print "$n\n";
print_r($mya);
This program produces the following result.
two
Array
(
[0] => zero
[1] => one
)