How to find elements in array that contain a given substring?

后端 未结 4 2018
礼貌的吻别
礼貌的吻别 2020-12-21 12:02

I have 3 strings, I would like to get only the equal strings of them, something like this:

$Var1 = \"Sant\";
$Array[] = \"Hello Santa Claus\";   // Name_1
$A         


        
4条回答
  •  清酒与你
    2020-12-21 12:19

    If you want to "filter" your "array", I recommend using the php function called array_filter() like this:

    Code:

    $Var1 = "Sant";
    $Array=["Hello Santa Claus","Easter Bunny","Santa Claus"];
    
    var_export(array_filter($Array,function($v)use($Var1){return strpos($v,$Var1)!==false;}));
    

    Output:

    array (
      0 => 'Hello Santa Claus',
      2 => 'Santa Claus',
    )
    

    array_filter() needs the array as the first parameter, and the search term inside of use(). The return portion tells the function to retain the element if true and remove the element if false.

    The benefit to this function over a foreach loop is that no output variables needs to be declared (unless you want one). It performs the same iterative action.

提交回复
热议问题