Carlos Barbosa
Carlos Barbosa

Reputation: 1432

Fastest way to check if a given array value matches another array value?

I know this is a 0(n) relationship, where we need to check for every single row of array for membership, but what is the fastest way to do the check?

$x = [["id" =>61, "name" => "jill"],["id" =>1, "name" => "john"],];
$y = [["id" =>89, "state" => "drunk"],["id" =>61, "state" => "sleep"]];

$z = array_values_collide($x, $y, "id");

where z should return:

$z = [["id" =>61, "name" => "jill", state => "sleep"];

Upvotes: 0

Views: 887

Answers (2)

Martin Rothenberger
Martin Rothenberger

Reputation: 828

Use array_intersect_assoc to get the values which are present both arrays. And/or check the other intersect commands.

http://www.php.net/manual/en/function.array-intersect-assoc.php

Upvotes: 0

Diego
Diego

Reputation: 18359

If I understand correctly, you want all elements in $x that are also in $y. The result is called the intersection of both arrays. See function array_intersect_assoc. I am sure PHP developers took care of implementing it to be as fast as possible.

Upvotes: 1

Related Questions