PHP Array Searching
In this page:
Finding Values with in_array
in_array() checks whether a given value exists anywhere in an array and returns a simple boolean, which is the quickest way to answer a yes/no membership question like 'is this email already registered?'
Example: Finding Values with in_array
<?php
$emails = ["[email protected]", "[email protected]"];
var_dump(in_array("[email protected]", $emails));
?>
Login to try C/C++/Java/PHP code in the editor
Finding Keys with array_search
array_search() is similar to in_array() but returns the key of the first matching element instead of just true/false, letting you locate exactly where a value lives so you can update or remove it.
Example: Finding Keys with array_search
<?php
$fruits = ["apple", "banana", "cherry"];
$key = array_search("banana", $fruits);
echo $key;
?>
Login to try C/C++/Java/PHP code in the editor
Checking Key Existence
array_key_exists() checks for the presence of a key rather than a value, which matters because a key can exist with a null or empty value that in_array() would otherwise miss depending on strict comparison settings.
Example: Checking Key Existence
<?php
$data = ["email" => null];
var_dump(array_key_exists("email", $data));
var_dump(in_array(null, $data, true));
?>
Login to try C/C++/Java/PHP code in the editor
Searching with array_keys
Both in_array() and array_search() accept an optional strict parameter, and passing true forces === comparison instead of the default loose ==, avoiding surprising matches like 0 == abc in older PHP versions.
Example: Searching with array_keys
<?php
$values = [0, "abc", false];
var_dump(in_array("abc", $values));
var_dump(in_array("abc", $values, true));
?>
Login to try C/C++/Java/PHP code in the editor
Advanced Search using array_filter
For associative arrays, combining array_column() with array_search() lets you search by a specific field across a list of records, such as finding the array index of the user whose id matches a given value.
Example: Advanced Search using array_filter
<?php
$users = [["id" => 1, "name" => "Alice"], ["id" => 2, "name" => "Bob"]];
$ids = array_column($users, 'id');
$index = array_search(2, $ids);
echo $index;
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: