It is said on the following link:
Using the strpos() function
The strpos() function is used to search for a string or character within a string.

If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE.

https://www.tutorialspoint.com/php/php_strings.htm

Isn't the following supposed to output to screen "FALSE" ? I do not see this happening.

<?php
  echo strpos("Hello world!","s");
?> 

Recommended Answers

All 5 Replies

Worked for me. It returned a zero.
How did I test that?
echo strpos("Hello world!","s")==0

Also works. (adding with edit.
echo strpos("Hello world!","s")==FALSE;

In addition: it happens because it's boolean FALSE which is converted automatically to an empty string, you won't get a string FALSE, for example:

echo "FALSE"; # string, printed
echo 'FALSE'; # string, printed
echo FALSE;   # boolean, empty

From the manual:

A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

Link: http://php.net/manual/en/language.types.string.php#language.types.string.casting

In your case you can write:

$pos = strpos('Hello World!', 's');

if(FALSE !== $pos)
{
    # success
}

else
{
    # not found
}

Just for fun, time to see why we would use triple equal signs here.

<?php
echo 1, strpos("Hello world!","s")==FALSE, PHP_EOL;
echo 2, strpos("Hello world!","s")===FALSE, PHP_EOL;
echo 3, strpos("Hello world!","s")==0, PHP_EOL;
echo 4, strpos("Hello world!","s")===0, PHP_EOL;
?>

I'm confused why PHP chose to return FALSE rather than -1 (not found) like C++ (string::npos) here. It's returning an index. Why bother mixing types? What's the advantage? A negative integer representing an obviously non-existent index if not found or a non-negative integer representing the real index if found seems more intuitive than an integer if found and "FALSE" if not found. To me at least.

commented: One of the things that bothers me too in PHP. +14
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.