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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-12-02 14:51:12743browse

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

Filtering Multidimensional Arrays Based on Partial Match

In this programming task, we present you with a scenario where you require a function to filter a multidimensional array based on a partial match of a search value. Consider the given array:

array(
 [0] =>
  array(
   ['text'] =>'I like Apples'
   ['id'] =>'102923'
 )
 [1] =>
  array(
   ['text'] =>'I like Apples and Bread'
   ['id'] =>'283923'
 )
 [2] =>
  array(
  ['text'] =>'I like Apples, Bread, and Cheese'
  ['id'] =>'3384823'
 )
 [3] =>
  array(
  ['text'] =>'I like Green Eggs and Ham'
  ['id'] =>'4473873'
 ) 
etc.. 

We seek to search for the needle "Bread" in the array and obtain the following result:

[1] =>
  array(
   ['text'] =>'I like Apples and Bread'
   ['id'] =>'283923'
 )
 [2] =>
  array(
  ['text'] =>'I like Apples, Bread, and Cheese'
  ['id'] =>'3384823'

To accomplish this, we leverage the array_filter function, which allows us to define a callback that determines which elements to retain in the array based on a given condition. In this scenario, we return true if the 'text' field contains the search_text, indicating that the element should be kept. A return value of false would remove the element.

The implementation looks like this:

$search_text = 'Bread';

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

By implementing this method, you effectively filter the multidimensional array and return only the elements that partially match the search value you specify. For further guidance, refer to the following resources:

  • [PHP array_filter](https://www.php.net/manual/en/function.array-filter.php)
  • [PHP strpos return values](https://www.php.net/manual/en/function.strpos.php)

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