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

How Can I Filter a Multidimensional Array Using Partial String Matching in PHP?

Susan Sarandon
Release: 2024-12-02 02:36:09
Original
224 people have browsed it

How Can I Filter a Multidimensional Array Using Partial String Matching in PHP?

Filtering Multidimensional Arrays Based on Partial Match of Search Value

In certain scenarios, it becomes necessary to filter data stored in multidimensional arrays based on a partial match of a specified search value.

Suppose we have an array structured as follows:

$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 assume we want to search for a specific needle, such as "Bread." To filter the array and retrieve elements that contain the partial match, we can leverage the array_filter function.

$search_text = 'Bread';

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

The array_filter function accepts two parameters: the input array and a callback function. The callback function is responsible for evaluating whether each element should be retained or removed from the array. In our case, the callback function checks if the 'text' field of the element contains the specified search term. If so, it returns true, indicating that the element should be retained.

Upon execution, the filtered_array will contain the following elements:

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

This approach effectively filters the multidimensional array, returning only the elements that satisfy the partial match condition.

The above is the detailed content of How Can I Filter a Multidimensional Array Using Partial String Matching in PHP?. For more information, please follow other related articles on the PHP Chinese website!

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