Home > Backend Development > PHP Tutorial > How to Efficiently Filter a Multidimensional Array Using Partial String Matching in PHP?

How to Efficiently Filter a Multidimensional Array Using Partial String Matching in PHP?

Mary-Kate Olsen
Release: 2024-11-29 19:09:14
Original
685 people have browsed it

How to Efficiently Filter a Multidimensional Array Using Partial String Matching in PHP?

Filter Multidimensional Array Based on Partial Match of Search Value

Filtering multidimensional arrays can often pose challenges, especially when searching for partial matches. This article introduces a method to efficiently filter an array using array_filter to find elements with text that partially matches a given search value.

Consider the following example:

$array = [
    [
        'text' => 'I like Apples',
        'id' => '102923'
    ],
    [
        'text' => 'I like Apples and Bread',
        'id' => '283923'
    ],
    [
        'text' => 'I like Apples, Bread, and Cheese',
        'id' => '3384823'
    ],
    [
        'text' => 'I like Green Eggs and Ham',
        'id' => '4473873'
    ]
];
Copy after login

Let's filter this array for the needle "Bread":

$search_text = 'Bread';

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

The result will be the following:

[
    [
        'text' => 'I like Apples and Bread',
        'id' => '283923'
    ],
    [
        'text' => 'I like Apples, Bread, and Cheese',
        'id' => '3384823'
    ]
];
Copy after login

This solution utilizes array_filter to pass a callback function that checks each element's text value for a partial match of $search_text using strpos.

The above is the detailed content of How to Efficiently Filter a Multidimensional Array Using Partial String Matching 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