php array functions with examples
Example 1: common array methods php
sizeof($arr)
is_array($arr)
in_array($var, $arr)
print_r($arr)
array_merge($arr1, $arr2)
array_values($arr)
array_keys($arr)
array_pop($arr)
array_push($arr, $val)
array_shift($arr)
sort($arr)
array_map('function_name', $arr)
array_flip($arr)
array_reverse($arr)
array_rand($arr)
array_slice($arr, $offset, $length)
Example 2: create a function that checks the values of the indexes in two arrays and keep a score
const triplets = (arr1,arr2) => {
let score1 = 0;
let score2 = 0;
let resultArr = [0,0]
for (let i = 0; i < arr1.length; i++){
if(arr1[i] === arr2[i]) {
resultArr[0] = score1
resultArr[1] = score2
} else if (arr1[i] > arr2[i]) {
score1++
resultArr[0] = score1
} else if (arr1[i] < arr2[i]) {
score2++
resultArr[1] = score2
}
}
return resultArr
}
Example 3: php array
<?php
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo"
)
)
);
var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
?>
Example 4: php array functions
array_change_key_case() Changes all keys in an array to lowercase or uppercase
array_chunk() Splits an array into chunks of arrays
array_column() Returns the values from a single column in the input array
array_combine() Creates an array by using the elements from one "keys" array and one "values" array
array_count_values() Counts all the values of an array
array_diff() Compare arrays, and returns the differences (compare values only)
array_diff_assoc() Compare arrays, and returns the differences (compare keys and values)
array_diff_key() Compare arrays, and returns the differences (compare keys only)
array_diff_uassoc() Compare arrays, and returns the differences (compare keys and values, using a user-defined key comparison function)
array_diff_ukey() Compare arrays, and returns the differences (compare keys only, using a user-defined key comparison function)
array_fill() Fills an array with values
array_fill_keys() Fills an array with values, specifying keys
array_filter() Filters the values of an array using a callback function
array_flip() Flips/Exchanges all keys with their associated values in an array
array_intersect() Compare arrays, and returns the matches (compare values only)
array_intersect_assoc() Compare arrays and returns the matches (compare keys and values)
array_intersect_key() Compare arrays, and returns the matches (compare keys only)
array_intersect_uassoc() Compare arrays, and returns the matches (compare keys and values, using a user-defined key comparison function)
array_intersect_ukey() Compare arrays, and returns the matches (compare keys only, using a user-defined key comparison function)