Home > Backend Development > PHP Tutorial > How Can I Efficiently Filter Multidimensional Arrays for Partial Matches in PHP?

How Can I Efficiently Filter Multidimensional Arrays for Partial Matches in PHP?

Linda Hamilton
Release: 2024-11-27 02:14:11
Original
763 people have browsed it

How Can I Efficiently Filter Multidimensional Arrays for Partial Matches in PHP?

Filtering Multidimensional Arrays for Partial Matches

Searching for specific values within multidimensional arrays can be challenging. To address this issue, we can utilize array_filter to efficiently filter based on partial matches.

Consider the given array containing text and ID key-value pairs. To filter this array for the needle "Bread," we employ array_filter with a custom callback function. The callback compares each element's 'text' value with the search term using strpos. If the search term is found within the 'text' value, the element is retained, otherwise, it is removed.

<?php
$search_text = 'Bread';

$filtered_array = array_filter($array, function($el) use ($search_text) {
        return ( strpos($el['text'], $search_text) !== false );
    });
?>
Copy after login

This filtering technique provides a convenient and flexible way to retrieve only the relevant elements from multidimensional arrays based on partial matches. For further details, refer to the documentation for array_filter and strpos.

The above is the detailed content of How Can I Efficiently Filter Multidimensional Arrays for Partial Matches in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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