How to Filter Array Rows by Matching Values Using array_uintersect()?

Linda Hamilton
Release: 2024-10-23 16:06:02
Original
143 people have browsed it

How to Filter Array Rows by Matching Values Using array_uintersect()?

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

Explanation:

  • The array_uintersect() function takes two arrays and a callback as arguments.
  • The callback function is invoked for each element from both arrays, and it should return 0 if the elements are considered equal, 1 if the first element is greater, and -1 if the second element is greater.
  • If an element does not have an id column, its raw value is used for comparison.
  • The result is an array containing only the rows from $arr1 where the id column matches a value in $arr2.

Benefits of array_uintersect():

  • It is a native PHP function, ensuring efficiency and compatibility.
  • It performs sorting while evaluating, which optimizes performance.
  • It provides a concise and readable solution compared to iterated calls of in_array().

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!