Usage of Important Array Functions in PHP
PHP is a server side scripting language designed for web development by Rasmus Lerdorf in 1994.
Let's see now usage of important Array functions in PHP:-
count($arr) - counting the array/object length.
array_pop($arr) - remove end element from array.
array_shift($arr) - remove first element from array.
array_filter($arr) - to remove empty value arrays.
$arr1 = array(1,2);
$new_arr = array_filter($arr1,function($v){
if($v > 1){
return $v;
}
});
array_reverse($arr) - to change the order of array from asc to desc and desc to asc
array_sum($arr) - to sum of integers array or numbers array, if array has both string and number so it only sum numbers and if all are strings so result will be 0.
in_array(‘value’,$arr) - use index array it directly checks with value and for associative array it targets the value not key.
array_key_exists(‘key’,$arr) - it only works with key pair arrays like associative or multidimensional.
end($arr) - get the last value of any type an array.
array_merge($arr1,$arr2) - used for merging two arrays.
array_combine($keys_arr,$values_arr) - It takes the value of an array to combine and both array elements should be equal otherwise it will give a warning error.
array_map($func,$arr) - It is useful in any array to do any functional changes in each value of the array.
$arr1 = array(1,2); $name = "Riya";
$new_arr = array_map(function($v){
return $v * 5;
}, $arr1);
Use of closure in it
$new_arr = array_map(function($v) use ($name){
return $name.'-'.$v;
}, $arr1);
array_walk($arr, ’functionName’, $optionalParam) - used for index array and associative array but this will not create a new array.
array_walk_recursive($arr, ’functionName’, $optionalParam) - used for multidimensional array works sams as array_walk function but array_walk does not get array inside array values that’s why for multidimensional arrays it is useful.
array_unique($arr) - removes duplicate values from array.
array_fill(index.number,value) - it is useful for printing anything several times as much as you want. Here index is from array element, number is to array element, and value whatever you want to print.
array_diff($arr1, $arr2) - shown different elements between both arrays.
explode() - breaks a string into an array based upon any string, letter, chars.
split() deprecated, preg_split() - breaks string into an array based upon regular expression.
Thanks for reading this article guys 😊
Comments
Post a Comment