How does strpos() function in PHP return int as well as boolean?

412 Views Asked by At

This is what w3School says about the strpos() function :

Returns the position of the first occurrence of a string inside another string, or FALSE if the string is not found.

How is the function defined? Is it possible to write such functions which returns values of 2 different datatypes in other languages as well?

2

There are 2 best solutions below

1
On BEST ANSWER

Many dynamically typed languages allow you to return whatever you want from a function. Strongly typed languages generally don't.

In PHP a function can return anything it wants, including booleans, ints, strings, null, arrays, all kinds of objects, whatever you need. It's the same in for example Javascript and Lua, which are also dynamically typed.

Just make sure to check the return type of the function if it can be different kinds of things. Especially with things like int(0) and false, which are considered equivalent if you use an == comparison. Use === to make sure it's the right type.

0
On

Other languages do not have loosely typed variables and function returns. Take for example C.

Taken from php.net:

PHP is a dynamic, loosely typed language, that uses copy-on-write and reference counting.