Row Subset Based on Column Value Inclusion
Consider an array, $arr1, with multiple columns and a second flat array, $arr2, containing specific id values. The objective is to filter $arr1 to retain only those rows where a column value matches any of the values in $arr2.
Previous attempts using filter functions or array_search have proved unsuccessful. A practical solution involves employing the native PHP function, array_uintersect().
This function utilizes an anonymous callback function that evaluates the id column (or falls back to the parameter value if not present) within both input arrays. The comparison checks for equality between the values.
Within the callback, the operator => is employed to capture the input array variables $a and $b, and the ternary operator ?: assigns a non-null return value.
Under the hood, array_uintersect performs sorting during the evaluation process, optimizing performance and executing significantly faster than iterative in_array() calls.
The code below demonstrates the solution:
<code class="php">var_export( array_uintersect( $arr1, $arr2, fn($a, $b) => ($a['id'] ?? $a) <= ($b['id'] ?? $b) ) );</code>
The above is the detailed content of How to Filter Array Rows Based on Column Value Matching Specific Values?. For more information, please follow other related articles on the PHP Chinese website!