2

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...
}
7
  • try to change your comparison operator !== to != Commented Mar 13, 2017 at 20:22
  • Doesn't work how? Commented Mar 13, 2017 at 20:23
  • show how did you call test(...) function Commented Mar 13, 2017 at 20:25
  • @u_mulder it allways returns false Commented Mar 13, 2017 at 20:27
  • 1
    @coderodour No. You want the !==. strpos can return both false and 0 with opposite meanings (false means not found, 0 means found at first character). If you made the comparison !=, if the string started with the substring, it would be found and return 0, which is a falsy value (can be coerced to false) so the type strict comparison is needed. Commented Mar 13, 2017 at 20:34

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

i see your point.... but it still returns false every run... maybe there is a problem checking or substrings with "-" and that type of character?
We both got the haystack and the needle mixed up. Swap the $item and $substring in strpos

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.