array function in php code example
Example 1: php delete element by value
$colors = array("blue","green","red");
if (($key = array_search("green", $colors)) !== false) {
unset($colors[$key]);
}
Example 2: 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 3: php if array has mroe than one subarray
if (count($arr) > 1) {
....
}
Example 4: how to remove keys in subarray php
print_r(deep_delete_keys($arr,'country'));
function deep_delete_keys($arr, $keys) {
if (!is_array($keys)) $keys = array($keys);
$filteredArr = array_diff_key( $arr, array_flip( $keys ) );
foreach ($filteredArr as &$val) {
if (is_array($val)) {
$val = deep_delete_keys($val, $keys);
}
}
return $filteredArr;
}
Example 5: 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 6: 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"]);
?>