MENU
Searching and Counting
array_key_exists($m,$arr) returns true if the key $m can be found in $arr. in_array ($m, $arr[,$b=false]) returns true if the value $m can be found in $arr. If $b is true, the types are also compared. array_search($m,$arr[,$b=false]) returns the first matching key of the value $m. FALSE is returned if the value does not exist. If $b is true, the types are also compared. count($arr[,$i]) or sizeof($arr[,$i]) returns the number of elements in $arr. If $i is set to COUNT_RECURSIVE, the elements in sub arrays will be counted as well. array_count_values($arr) returns an array which uses the values of $arr as keys, and their frequencies as values.<!DOCTYPE html><html><head></head>
<body>
<?php
$a=["hello",1,1,"hello",1,2];
print_r(array_count_values($a));
?>
</body></html>Array ( [hello] => 2 [1] => 3 [2] => 1 )
PHP 8.1’s array_is_list($arr) returns true if $arr’s keys are the integers 0, 1, 2, and so on with no gaps. In other words, it checks whether $arr is a plain ‘list’ rather than an associative array.
<!DOCTYPE html><html><head></head>
<body>
<?php
$fruit = ["a" => "apple", "b" => "banana", "c" => "cherry"];
echo array_key_first($fruit) . "<br />";
echo array_key_last($fruit) . "<br />";
var_dump(is_countable($fruit));
var_dump(is_countable("not an array"));
$list = ["x", "y", "z"];
$assoc = ["a" => "x", "b" => "y"];
$gappy = [1 => "x", 2 => "y"];
var_dump(array_is_list($list));
var_dump(array_is_list($assoc));
var_dump(array_is_list($gappy));
?>
</body></html>a
c
bool(true) bool(false) bool(true) bool(false) bool(false)
c
bool(true) bool(false) bool(true) bool(false) bool(false)