In your example the function strstr
did not work because it works to return an excerpt of a string contained in another, not valid for array
.
So what to do?
If the need is to check whether within the 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 somewhere in the strings that are inside the array
.
Behold:
$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 still optionally use the function preg_grep
followed by a count
to know if any reference has been found. I believe you will need to use less code in this case, but you will need 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 using the function array_filter
. But in this case, when the situation is complex, as shown above, I always like to leave a function ready for this, in case 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
- Counts the values of array
or a class that implements Countable
array_filter
- Removes the values of array
according to the callback. Will be removed if return FALSE
strpos
- Checks if the string contains the specified snippet.
You could check like this:
array_contains_value('facebook.com', ['www.facebook.com', 'www.google.com']);
Two things: 1 - That the array is actually not an array, but a string. The correct writing of the array would be
$array = array("facebook.com", "google.com", "twitter.com");
2 - That the informed reference also does not exist in the "Array".– Adriano Luz
Right @Adrianoluz , but it has to be that way?
$array = "facebook.com, google.com, twitter.com";
because it’s in the database, I just gave an example there of how it’s in the table.– Fernando Oliveira
power even can, if it is an example or exercise. But you need to understand that your bank is not respecting the Normal Way 1
– Adriano Luz
@Fernandooliveira took the liberty of correcting the title. It was leading to the wrong answers.
– Wallace Maxters