1

For some reason I can't get strpos to work to search my array, even if $jobList[1] and $titlesearch are the same values... Sorry if it's something obvious but I'm still pretty new to coding!

I begin with my $data array which looks like this:

Array
(
    [0] => P0001    Lifeguard   descexample 18/09/18    parttime    fixedterm       mail    vic

    [2] => P0002    IT Manager  descexample 18/09/18    fulltime    ongoing post    mail    sa

)

I then explode each of these entries into their own array...

for ($i = 0; $i < count($data); $i++) {
    $jobList = explode("\t", $data[$i]);
}

Array
(
    [0] => P0001
    [1] => Lifeguard
    [2] => descexample  
    [3] => 18/09/18
    [4] => parttime
    [5] => fixedterm
    [6] => 
    [7] => mail
    [8] => vic

)
Array
(
    [0] => P0002
    [1] => IT Manager
    [2] => descexample  
    [3] => 18/09/18
    [4] => fulltime
    [5] => ongoing
    [6] => post
    [7] => mail
    [8] => sa

)

Now I'm trying to search through these arrays from a user input, $titlesearch, and find it's matches with the job titles, $jobList[1]:

if (strpos($jobList[1], $titlesearch)) {
        echo "nice one";
    }

No matter what loops I try, the strpos never returns true, even if I echo the values and they both give the same result, so I'm really not sure what I'm doing wrong :'(

Any help is greatly appreciated!

4
  • 2
    That's because strpos doesn't return a boolean value. It returns the position in the substring was found (which may be 0) or -1 if not found. Commented Sep 18, 2018 at 7:47
  • 1
    $jobList = explode("\t", $data[$i]);->don't you think you are overwriting the values. you will not get the second array into that variable. Commented Sep 18, 2018 at 7:47
  • 1
    @Vince0789 strpos can return a boolean value. But it never returns -1, this is not javascript. Commented Sep 18, 2018 at 7:48
  • @u_mulder ah yes, you're right. The return value is boolean false if the substring is not found, however the function may also return 0 if the substring was found at the start of the string, so the comparison should still be carried out with the identical operator (===). Commented Sep 18, 2018 at 7:51

1 Answer 1

2

You should always compare the data type when using this function as it may not return a boolean and it can be missleading. Check documentation here

Try it something like this:

if (strpos($jobList[1], $titlesearch) !== false) {
        echo "nice one";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yay! This explains why it worked when I was messing around with it the other day too! Thankyou very much :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.