Search code examples
phpstrpos

strpos not working for first string among comma separated strings


See this demo

I have two lists of comma separated strings, and want to look for strings and return a message. I noticed that in the particular case that I look for the first string of the first list, it will not find it. If I move that string to another placement, it will. Can't understand why.

$dynamic_list = "AZ, CA, CO";
$static_list = "MN,WA,IA";

$search = "AZ";


if ( strpos($dynamic_list . ',' . $static_list, $search) == false && !empty($search) ) { // check string is not empty + that it is not on any of the lists
    echo 'not found: String '.$search.' was not found in lists';
} else {
    echo 'found';
}

Solution

  • Note our use of ===. Simply == would not work as expected because the position of 'A' in 'AZ' is the 0th (first) character. So === will do the job for you here. Let's try with ===

    See examples here: https://www.php.net/manual/en/function.strpos.php

    Warning

    This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

    <?php
    
    $dynamic_list = "AZ, CA, CO";
    $static_list = "MN,WA,IA";
    $search = "AZ";
    
    if (strpos($dynamic_list . ',' . $static_list, $search) === false) {
        echo 'not found: String '.$search.' was not found in lists';
    } else {
        echo 'found';
    }
    

    DEMO: https://3v4l.org/bo4Yjr