This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,
visit the help center.
Closed 7 years ago.
There are two arrays:
$strings = array('Apple', 'Banana', 'Orange');
$substrings = array('pp', 'range');
I want to get an array which contains all the strings, that match the substrings:
Array
(
[0] => Apple
[2] => Orange
)
Or with new indices:
Array
(
[0] => Apple
[1] => Orange
)
A simple solution that comes to mind: combine array_filter
and strpos
;
$strings = array('Apple', 'Banana', 'Orange');
$substrings = array('pp', 'range');
$result = array_filter($strings, function($item) use($substrings) {
foreach($substrings as $substring)
if(strpos($item, $substring) !== FALSE) return TRUE;
return FALSE;
});
To reset indices, you can use the array_values
function.
$strings = array('Apple', 'Banana', 'Orange');
$substrings = array('pp', 'range');
$newarray = array();
foreach ($strings as $string) {
foreach ($substrings as $substring) {
if (strstr($string, $substring)) {
array_push($newarray, $string);
}
}
}
in $newarray
you have the result
try array_search. looked at the second note at the bottom of this page http://php.net/manual/en/function.array-search.php for an example.
$arr=array();
foreach($substrings as $item)
{
$result=array_keys($strings,$item);
if ($result)
{
$arr=array_merge($arr,$result);
}
}
You can use array_filter for this:
$strings = array('Apple', 'Banana', 'Orange');
$substrings = array('pp', 'range');
$result = array_filter($strings, function($string) use ($substrings){
foreach($substrings as $substring)
if(strstr($string, $substring) !== false)
return true;
return false;
});
// $result is the result you want.