Home  >  Article  >  Backend Development  >  How to Filter Array Rows Based on Column Value Matching Specific Values?

How to Filter Array Rows Based on Column Value Matching Specific Values?

Linda Hamilton
Linda HamiltonOriginal
2024-10-23 18:57:31812browse

How to Filter Array Rows Based on Column Value Matching Specific Values?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn