Search code examples
phpmysqliwhile-loopstrpos

strpos - not giving expected results


I am trying to run through some info from my database to check if the itemcode is included as one of the items 'keys'.

I was expecting this code to show me only the rows where the code IS NOT a key - however I seem to get a mixture of results (some where the code is there and others where it isn't)

I have tried changing true to false and I get a similar set of results.

   while ($row = mysqli_fetch_array($query)){

        $itemcode = $row['itemcode'];
        $keys = $row['keys'];

        if (strpos($metakeywords, $itemcode) !== true) {
        echo 'code: ' . $itemcode . " keys: " . $metakeywords . "<br /><br />" ;
    }

Expected output:
code: ABC123 keys: planter, green, window
code: DEF456 keys: blue, outdoors, garden

Actual Output:
code: ABC123 keys: planter, green, window
code: CBA321 keys: red, indoors, planter, CBA321
code: DEF456 keys: blue, outdoors, garden
code: FED654 keys: pink, plant, FED654, self-watering

Can anyone help?


Solution

  • strpos() doesn't return true when it finds a match, it returns the position of the match.

    If you want to know when there's no match, use:

    if (strpos($metakeywords, $itemcode) === false) {
    

    You could probably do this entirely in the SQL query, rather than in PHP, though.