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
Mary-Kate OlsenOriginal
2024-11-29 19:09:14783browse

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'
    ]
];

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);
});

The result will be the following:

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

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!

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