Search for a string or part of string in PHP

后端 未结 7 1652
春和景丽
春和景丽 2020-12-06 16:14

I am doing a very small online store application in PHP. So I have an array of maps in PHP. I want to search for a string (a product) in the array. I looked at array_search

7条回答
  •  [愿得一人]
    2020-12-06 17:08

    array_filter lets you specify a custom function to do the searching. In your case, a simple function that uses strpos() to check if your search string is present:

    function my_search($haystack) {
        $needle = 'value to search for';
        return(strpos($haystack, $needle)); // or stripos() if you want case-insensitive searching.
    }
    
    $matches = array_filter($your_array, 'my_search');
    

    Alternatively, you could use an anonymous function to help prevent namespace contamination:

    $matches = array_filter($your_array, function ($haystack) use ($needle) {
        return(strpos($haystack, $needle));
    });
    

提交回复
热议问题