Home >Backend Development >PHP Tutorial >How to Retain Array Rows with Matching Column Values from a Flat Array?
Retain Array Rows with Matching Column Values from a Separate Flat Array
Given an array $arr1 with multiple columns and a second flat array $arr2 containing a list of specific column values, the objective is to filter $arr1 and extract only the rows where the values in a particular column match the elements in $arr2.
Solution:
To efficiently perform this task, array_uintersect() can be employed. This native function utilizes a sorting algorithm during comparison to enhance execution speed. It takes two arrays and a custom callback function to determine the comparison logic.
In the provided code, the callback function leverages array destructuring to access the id column from each element of $arr1 and $arr2. If the id column does not exist, it defaults to the parameter's value.
The comparison checks if the id values from both arrays are equal, ensuring that the rows in $arr1 match the values in $arr2. The result is a new array containing only the desired rows from $arr1.
This approach offers superior performance to iterative calls of in_array() due to minimized function calls and optimized execution time.
The above is the detailed content of How to Retain Array Rows with Matching Column Values from a Flat Array?. For more information, please follow other related articles on the PHP Chinese website!