← Back to PHP Course | Chapter 7: Arrays | Lesson 12 of 13

PHP Array Searching

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
<?php
$emails = ["[email protected]", "[email protected]"];
var_dump(in_array("[email protected]", $emails));
?>

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
<?php
$fruits = ["apple", "banana", "cherry"];
$key = array_search("banana", $fruits);
echo $key;
?>

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
<?php
$data = ["email" => null];
var_dump(array_key_exists("email", $data));
var_dump(in_array(null, $data, true));
?>

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
<?php
$values = [0, "abc", false];
var_dump(in_array("abc", $values));
var_dump(in_array("abc", $values, true));
?>

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
<?php
$users = [["id" => 1, "name" => "Alice"], ["id" => 2, "name" => "Bob"]];
$ids = array_column($users, 'id');
$index = array_search(2, $ids);
echo $index;
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.