-5

Why does the following return 1 instead of true?

echo 5===5;  //1;
oxk4r
  • 452
  • 6
  • 17

3 Answers3

8

First of all, echo is not a function, it is a language construct and it does not actually "return" anything. echo is for outputting strings. The reason it outputs (not returns) 1 instead of true is because true is not a string, it is a boolean value and therefore when it is typecast to a string, PHP converts it to "1". If you want to see the real value of something, you need to use something like var_dump().

var_dump(true);
var_dump((string) true);
var_dump(5 === 5);
var_dump(false);
var_dump((string) false);
var_dump(5 === 6);

Output:

bool(true)
string(1) "1"
bool(true)
bool(false)
string(0) ""
bool(false)
Mike
  • 23,542
  • 14
  • 76
  • 87
  • `echo` is essentially output, so when you say 'it does not actually "return" anything', it is incorrect. In a way, it returns a result to the browser, the cli/terminal, etc... The main point is as noted in the documentation quoted below. The real issue lies with the boolean to string conversion. – Blue Feb 14 '18 at 00:49
  • 1
    @FrankerZ Output is not returning, just as sending a mail is not returning to the mail server and executing a query is not returning to the database server. Even from the [docs](http://php.net/echo) "*The major differences to print are that echo accepts an argument list and doesn't have a return value.*" – Mike Feb 14 '18 at 01:50
  • @FrankerZ I understood the question and I know what the OP meant, I just wanted to make a note that the terminology used was incorrect. I realize this is a side issue, which is why the rest of the answer attempts to actually answer the question. – Mike Feb 14 '18 at 01:52
3

According to the PHP documentation, for string comparison:

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.

In simplistic terms 5===5 is true. The output of it though, when you cast it to a string is "1" (As noted above). To return the type/value of a string, you should use var_dump(), which will show the correct type:

var_dump(5===5); //bool(true);

See this output.

Blue
  • 22,608
  • 7
  • 62
  • 92
1

you can try also: echo (1===1) === true or echo true ;)

echo casts boolean to string.

user1838937
  • 289
  • 4
  • 13