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
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.
You should do it like this. You can use stristr
but you have to flip arguments because you are passing wrong arguments. First argument should be haystack
and second should be needle
.
Try this code snippet here
ini_set('display_errors', 1);
$Var1 = "Sant";
$Array[] = "Hello Santa Claus"; // Name_1
$Array[] = "Santa Claus"; // Name_2
foreach ($Array as $name)
{
if (stristr($name,$Var1)!==false)
{
echo $name;
echo PHP_EOL;
}
}
Your code will work too like below:-
foreach ($Array as $name)
{
if (stristr($name,$Var1)!==false)
{
echo $name;
echo PHP_EOL;
}
}
Output:- https://eval.in/812376
You can use php strpos() function also for this purpose
foreach($Array as $name)
{
if ( strpos($name,$Var1)!==false)
{
echo $name;
echo PHP_EOL;
}
}
Output:-https://eval.in/812371
Note:- In Both function the first argument is the string in which you want to search the sub-string. And second argument is sub-string itself.
you can use strpos()
function of php to identify if a string consist a substring or not as
$a = 'Sant';
foreach($Array as $name)
{
if (strpos($name, $a) !== false) {
echo $name;
}
}