Search code examples
phpstringstrpos

strpos doesn't work with searching a term start with X


I need to change the length of decimal numbers according to $assetName. To do that I'm using strpos like so:

if (strpos($assetName, 'JPY') || strpos($assetName, 'XAG'))
{
    $decimal = 3;
}
elseif (strpos($assetName, 'OIL') || strpos($assetName, 'XAU'))
{
    $decimal = 2;
}
else
{
    $decimal = 5;
}

It doesn't work with XAG and XAU while it's working with JPY and OIL. If I tried with XAG or XAU $decimal becomes equal to 5. If I use AGU instead of XAG, it works when $assetName = XAGUSD.

I'm guessing X in the beginning causes the problem but I can't find the solution.


Solution

  • You should check strpos with strict type checking

    strpos($assetName, 'JPY') !== false
    

    Because when searched string happened to match at 0th index then its false in if statement but not false if checked with strict type comparison.

    Note:- Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.

    Returns FALSE if the needle was not found.