Home > Backend Development > PHP Tutorial > 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
Release: 2024-10-23 18:57:31
Original
924 people have browsed it

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template