PHP array_search() Function

In the realm of PHP programming, arrays stand as fundamental data structures. Manipulating arrays efficiently is key, and PHP offers an array of functions to simplify the process. One such function, array_search(), is a hidden gem that can streamline your array-related tasks. In this blog post, let's uncover the capabilities of the PHP array_search() function and see how it can become your go-to tool for array value retrieval.

Syntax:

array_search($value, $array, $strict = false)

Example


<?php
    $array 
= ["Apples","Bananas","Cherries"];
    
    echo 
array_search("Bananas",$array);
    
    
// OUTPUT : 1;
?>

Keep in mind that array_search() locates the first occurrence of the value and returns its key. If there are multiple instances of the same value, only the key of the first one will be returned. For a hunt for all occurrences, a custom loop or function would be required.

Example


<?php
    $array 
= [
            
"key0"=>"Apples",
            
"key1"=>"Bananas",
            
"key2"=>"Cherries"
        
];
    
    echo 
array_search("Bananas",$array);
    
    
// OUTPUT : key1;
?>

Example

Search a value in Multidimensional Array.


<?php
    $array 
= array(
        array(
            
"id"=>1,
            
"name"=>"test name 1",
            
"email"=>"test1@email.com"
        
),
        array(
            
"id"=>2,
            
"name"=>"test name 2",
            
"email"=>"test2@email.com"
        
),
        array(
            
"id"=>3,
            
"name"=>"test name 3",
            
"email"=>"test3@email.com"
        
),
    );
    
    
// get all id's in array
    
$array_column array_column($array'id');
    
    
// search id 2;
    
$key array_search(2$array_column);
    
    echo 
$array[$key]['name'];
    
    
// OUTPUT : test name 2;
?>

The PHP array_search() function might be short and sweet, but it packs a punch in simplifying value retrieval from arrays. Whether you need to hunt down a value or match it precisely with its data type, array_search() has got your back. Just remember its knack for uncovering the first match and consider alternative strategies for dealing with multiple occurrences. As you navigate the vast landscape of PHP array manipulation, array_search() is a trusty tool you can count on.

Share