Reputation: 557
I have the following array:
$historicalFullList = ['Fecha','H-kWH-Total','H-kWH-Pico','H-kWH-Resto','H-kWH-Valle','H-Acum-Pico','H-Acum-Resto','H-Acum-Valle','H-Fecha-Pico','H-Fecha-Resto','H-Fecha-Valle','H-kW-Pico','H-kW-Resto','H-kW-Valle','H-kVARH-Total','error','factMult','H-kW-Pico-C','H-kW-Resto-C','H-kW-Valle-C'];
I want to create a function to find if the substring 'H-k' exists in the array. (in this example array it should return TRUE)
For some reason the following code doesn't work. Is there a better way to do this?
function test($substring, $array){
foreach ($array as $item){
if (strpos($substring, $item)!== false){
return true;
}else{
return false;
}
}
}
then called it..
if (test('H-k',$historicalFullList)){
do stuff...
}
Upvotes: 2
Views: 2934
Reputation: 1721
move your return false out of the foreach, else it will return false after the first comparison if it doesn't contain $substr
.
function test($substring, $array){
foreach ($array as $item){
if (strpos($item,$substring)!== false){
return true;
}
}
return false;
}
Also, swap the needle and the haystack for strpos.
Upvotes: 7