In your example, the strstr
function did not work because it works to return an excerpt from a string contained in another, not for array
.
So what to do?
If you need to check if within array
$arrayIds
there is a string that contains part of another, I suggest you combine array_map
with the desired function. Then use in_ array
to see if there is any true occurrence for this function.
An example, I want to know if "bola"
exists in some part of the strings that are within array
.
See:
$produtos = array(
'bola vermelha',
'boneca Barbie',
'caneca de ouro'
);
// Essa função será executada em cada item do array acima
$verifica_string = function ($value)
{
return strpos($value, 'bola') !== false;
};
$lista_de_verificacoes = array_map($verifica_string, $produtos);
var_dump(in_array(true, $lista_de_verificacoes , true)); // Retornará "true" se "bola" existir no array
You can optionally also use the preg_grep
function followed by a count
to see if any references have been found. I think you'll have to use less code in this case, but you'll have to use regular expression:
// Temos que escapar os valores por causa do "."
$refRegex = sprintf('/%s/', preg_quote('facebook.com'));
if (count(preg_grep($refRegex, $arrayIds))) > 0) {
// tem a string
}
There is also a third way, which is to use the array_filter
function. But in this case, when the situation is complex, like the one shown above, I always like to leave a function ready for this if it is necessary to reuse:
function array_contains_value($neddle, array $array)
{
return (boolean) count(array_filter($array, function ($value) use($neddle)
{
return strpos($value, $neddle) !== false;
}));
}
In the above function I use the following functions:
-
count
- Count the values of array
or a class that implements Countable
-
array_filter
- Removes the values of array
according to the callback. It will be removed if you return FALSE
-
strpos
- Checks whether the string contains the specified snippet.
You could check this out:
array_contains_value('facebook.com', ['www.facebook.com', 'www.google.com']);