Keep Array Rows Matching Values in a Flat Array
Background:
You have an array, $arr1, with multiple columns and another array, $arr2, containing a list of values. The goal is to filter $arr1 and retain only the rows where the id column matches any value in $arr2.
Solution:
Using array_uintersect():
The most efficient solution utilizes the array_uintersect() function, which compares elements from two arrays using a user-defined callback. In this case, the callback checks if the id values match.
var_export( array_uintersect( $arr1, $arr2, fn($a, $b) => ($a['id'] ?? $a) <=> ($b['id'] ?? $b) ) );
Explanation:
Benefits of array_uintersect():
The above is the detailed content of How to Filter Array Rows by Matching Values Using array_uintersect()?. For more information, please follow other related articles on the PHP Chinese website!