Search code examples
phploopssearchstrpos

PHP - strpos on array elements?


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!


Solution

  • 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";
    }