March 31, 2024
How to search a value from a 2-dimensional array in PHP
TechTechInfo.com » How to search a value from a 2-dimensional array in PHP

How to search a value from a 2-dimensional array in PHP

array search for 2-dimension array

The array is a collection of similar types of data. Here you will learn how to search a value from a single dimensional array as well as a 2-dimensional array. We will use the array_search function for this task.

Search for single Dimensional array:- 

$a=array("a"=>"red","b"=>"green","c"=>"blue");

echo array_search("red",$a);

Search for 2-Dimensional array:- 

$a = array(
        array(
        'id' => 5698,
        'first_name' => 'Peter',
        'last_name' => 'Griffin',
        ),
        array(
        'id' => 4767,
        'first_name' => 'Ben',
        'last_name' => 'Smith',
        ),
        array(
        'id' => 3809,
        'first_name' => 'Joe',
        'last_name' => 'Doe',
        )
    );

print_r($a);
//search first name of the user "Ben"
$firstnameArray = array_column($a,"first_name");
$value = array_search("Ben",$firstnameArray);
print_r($a[$value]);
die;

result:

In the above code first, we have created a new array by the array_column function for a column.

Here we have selected the first_name value to create a 1-dimensional array.

Ex: 

Array
(
    [0] => Peter
    [1] => Ben
    [2] => Joe
)

As we can see in the above array is single-dimensional so now we can add the array search function on this array that will return the index of value from the array 

$value = array_search("Ben",$firstnameArray);

Here array_search function will return  “1”.  As the index of “Ben” is 1 in the array. Now get the complete object from the parent array of the given index.

$result = $a[$value];

Final result:- 

Array

(
    [id] => 4767

    [first_name] => Ben

    [last_name] => Smith
)

 

Join the discussion

Translate »