Home >Backend Development >PHP Tutorial >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' ] ];
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); });
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', ] ]
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!