1

When using strpos() to find the following, there seems to be a bug.

$url = 'https://www.example.com';
if (strpos($url,'https')>0) the result is NOT found
if (strpos($url,'https',0)>0) the result is NOT found
if (strpos($url,'ttps')>0) the result is FOUND

Why is this happening? Even though I indicate the starting position of 0, it is not finding it. Is this a bug or is there something subtle I am missing? Thanks

  • Not a bug, misunderstanding how the function works. See the PHP API for example usage and details. Link is in the answer below. – Paul T. Nov 07 '21 at 00:55
  • It is a normal computing practice for a sequence (e.g. index in an array, position of substring, etc) to start from zero (0). I remember that this concept was taught in the 1st lesson of my course in C – Ken Lee Nov 07 '21 at 01:15

2 Answers2

2

Per the manual: https://www.php.net/manual/en/function.strpos.php

Returns the position of [...] the needle [...] note that string positions start at 0, and not 1. Returns false if the needle was not found

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.

You need to check for strpos === false. Otherwise PHP implicitly converts the 0 to false.

Titus
  • 72
  • 7
1

The return value 0 means that the substring was found at position 0 in the searched string.

So, the check for > 0 is wrong.

Documentation says:

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. 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.

https://www.php.net/manual/en/function.strpos.php

NineBerry
  • 26,306
  • 3
  • 62
  • 93