Home >Backend Development >PHP Tutorial >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!