5 most used php array functions

by Guna 2012-07-23 14:53:17

array_chunk:
This function will create multiple arrays from an array based on the size given.

Ex:

$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));

Output:
Array
(
[0] => Array
(
[0] => a
[1] => b
)

[1] => Array
(
[0] => c
[1] => d
)

[2] => Array
(
[0] => e
)

)


array_diff:
This function will returns an array containing values from $array1 which are not in $array2.

Ex:

$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result); // returns blue



array_slice:
This function returns part of an array, for example,

$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 0, 3); // returns "a", "b", and "c"



array_sum:
Returns sum of the values in givent array.

Ex:

$a = array(2, 4, 6, Cool
;
echo array_sum($a); // returns 20;



array_unique:
As the name suggests it returns unique array from the given array.

Ex:

$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result); // returns green,red,blue

Tagged in:

522
like
0
dislike
0
mail
flag

You must LOGIN to add comments