November 12, 2024
How to optimize the php two-dimensional search 
TechTechInfo.com » How to optimize the php two-dimensional search 

How to optimize the php two-dimensional search 

For search, the object or a row from a two-dimensional array most people use the for and foreach loop that consumes too much time to search if the record is large. It increases the iteration of a loop. That can consume too much memory and also raised the performance issue for the software if that code is accessible by multiple users through direct access or by API. 

$users = [

    [

        "user_id"=>1,

        "first_name"=>"Deepak",

        "last_name"=>"sharma"

    ],[

        "user_id"=>2,

        "first_name"=>"Tarun",

        "last_name"=>"sharma"

    ],[

        "user_id"=>3,

        "first_name"=>"vikas",

        "last_name"=>"sharma"

    ],[

        "user_id"=>4,

        "first_name"=>"Krishna",

        "last_name"=>"sharma"

    ]

];

Now in the above array we want the user name for the user which have the user id 3

Worst approach

foreach($users as $row) {

    if($row['user_id']==3){

        $userName = $row['first_name'];

    }

}

OR

for($i = 0;$i < count($users);$i++) {

    if($users[$i]['user_id']==3){

        $userName = $users[$i]['first_name'];

    }

}

Best approach

$key = array_search(3, array_column($users, 'user_id'));

$userName = $users[$key]['first_name'];

In this approach we are using the two array function first array_column and second array_search.

Array_column made an one dimensional array with that particular key. e.g user_id

Below given array will be return from the array column function.

$users =[

    [0]=>1,

    [1]=>2,

    [2]=>3,

    [3]=>4

];

Now array_search function will return you the key where value 3 is exist.

$key = array_search('3',$users);

Let suppose it return you the 2 because value 3 exist on the key 2.

$value = $users[$key]['first_name'];

Then you can easily access that value from the array 

Join the discussion