• :
  • :

PHP array_search: How to use in PHP with examples

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

PHP array_search : Detailed Guide

Description – PHP array_search

PHP array_search searches an array for a given value and returns the first matching key if successful.

Function Signature

array_search(mixed $needle, array $haystack, bool $strict = false): int|string|false

Arguments

  • needle – The value to be searched
  • haystack – The input array
  • strict – If this parameter is set to true, then the function performs strict type comparison

Notes

  • If strict is set to true, then the function matches identical elements. Identical elements have the same value and datatype.
  • If there is more than one match, the function returns the key of the first matching value only.

Return Type – PHP array_search

This function returns the matched key for the needle, else return false.

Warning

The function may return a falsey value instead of false. A falsey value is a non-boolean value that evaluates to false. It is safer to use the === operator for testing the return value of the array_search PHP.

Introduction 

PHP array_search is a convenient function to search through an array. This function searches for array values and returns the corresponding key for the value that matches. However, there is a drawback or, to be more precise, a limitation of the array_search. The limitation is that it returns the key for the first match and ignores all the other matches if there exists any.

PHP array_search

This article will explore the array_search PHP in-depth and find a workaround for the limitation of this function. We will also see a handy PHP function to search through a PHP multidimensional array. So, let’s get started right now!!

Usage Example#1 – PHP array_search

The following example shows the basic use of the array_search.

<?php
$developers = [
    "Anna" => "Javascript",
    "Edward" => "Java",
    "Rey" => "Python",
    "Sanjay" => "PHP",
    "Ali" => "C++",
    "Sarah" => "C#",
    "Bob" => "Android"
];
 
print_r(array_search("PHP", $developers));
 
//OUTPUT
//Sanjay
?>

The example uses an array with developers names as keys and their preferred skills as values. The needle in the example is “PHP”, and the haystack is the array. PHP array_search looks for a match in the array values and returns the corresponding key, “Sanjay.”

The flow in the example is pretty straightforward. However, the function description mentions that if more than one matching value, the array_search returns the key for the first matching value only. What can we do about it? What if we need all the corresponding keys for the matching values? Let’s see that in the next section.

An Alternative – PHP function array_keys 

So, the array_search matches values in PHP arrays and returns the key for the first match, ignoring all the others. Gladly, there’s a convenient workaround for this drawback. Don’t worry because we aren’t going to reinvent the wheel, instead use PHP array_keys.

The PHP array_keys function has a search_value argument. The search_value is what needle is in the array_search. The function returns keys for all the values matching the search_value. By the way, the array_keys function too has the strict argument.

Let’s reuse the array from the usage example and add a couple of PHP developers. The following example uses the array_keys function to return all the names having the value “PHP”.

<?php
$developers = [
    "Anna" => "Javascript",
    "Edward" => "Java",
    "Rey" => "Python",
    "Sanjay" => "PHP",
    "Ali" => "C++",
    "Sarah" => "C#",
    "Bob" => "Android",
    "Tyson" => "PHP",
    "Greg"  => "PHP"
];
 
print_r(array_keys($developers, "PHP"));
 
/*
OUTPUT
Array
(
    [0] => Sanjay
    [1] => Tyson
    [2] => Greg
)
*/
?>

Voila! The PHP array_keys function returns all the corresponding keys for the matching values. We have something else to show you, and that’s related to PHP multidimensional arrays.

PHP multidimensional arrays with the array_search 

In PHP 5.5.0 and later, we don’t have to write a user-defined function to search through a multidimensional array. Instead, PHP provides the array_column function. This function couples with the array_search to search through a multidimensional PHP array. Let’s see how.

<?php
$students_electives = [
    "Andy" => ["ID"=>"1001", "Elective"=>"Computer Science"],
    "Benjamin" => ["ID"=>"1002", "Elective"=>"Electronics"],
    "Catheline" => ["ID"=>"1003", "Elective"=>"Economics"],
    "Dexter" => ["ID"=>"1004", "Elective"=>"Computer Science"],
    "Eion" => ["ID"=>"1004", "Elective"=>"Computer Science"],
    "Franklin" => ["ID"=>"1005", "Elective"=>"Mathematics"],
    "Gina" => ["ID"=>"1006", "Elective"=>"Chemistry"],
    "Hudson" => ["ID"=>"1007", "Elective"=>"Electronics"],
    "Ira" => ["ID"=>"1008","Elective"=>"Mathematics"],
    "Jessica" => ["ID"=>"1009","Elective"=>"Economics"],
    "Kelvin" => ["ID"=>"1010","Elective"=>"Computer Science"],
    "Liam" =>  ["ID"=>"1011","Elective"=>"Mathematics"],
];
 
print_r(array_keys($students_electives)[array_search("1008",array_column($students_electives,"ID"))]);
 
//OUTPUT
//Ira
?>

The example may seem intimidating because there are several functions involved. So, let’s break it down for ease of understanding. The example breaks down to these three function calls in the following sequence.

$id_column = array_column($students_electives,"ID");
 
$index = array_search("1008",$id_column);
 
$student_names = array_keys($students_electives);
 
print_r($student_names[$index]);

Here’s the flow.

  • The array_column returns an array of student IDs in the same order as in the input array.
  • The PHP array_search returns the index of the “1008” student ID.
  • PHP array_keys return an array of student names.
  •  The name at $index is the student with the ID “1008”. So, array indexing gets the name from the array of students names.

Conclusion

So, the article gives an in-depth walkthrough of the function, its anatomy, usage, and some vital add-ons to help you get a broader insight about the array_search PHP. If you’ve made it to the conclusion, you have learned a new PHP function. To learn more about PHP, stay tuned for more upcoming informative articles and tutorials.

Want to explore more useful PHP tutorials?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

How to merge 2 arrays with the same keys in PHP

Difference between array_combine and array_merge in PHP

How to use associative array keys in PHP array_map function

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.