1

In php 7 I did this.The output should be 0 right?But I am getting a 1.Why is that?

 <?php
     echo "a"==0?1:0;
    ?>
1
  • echo "a"===0 ? 1 : 0; strict equality check Commented Nov 12, 2018 at 7:19

2 Answers 2

7

"a" == 0 evaluates to true.

Because any string is converted into an integer when compared with an integer. If PHP can't properly convert the string then it is evaluated as 0. So 0 is equal to 0, which equates as true.

If you want the answer as 0,

you should use === instead of ==,

Because the ordinary operator does not compare the types. Instead it will attempt to typecast the items.

Meanwhile the === takes in consideration type of items.

=== means "equals",

== means "eeeeh .. kinda looks like"

Also, the PHP manual for comparison http://au.php.net/manual/en/language.operators.comparison.php

// double equal will cast the values as needed followin quite complex rules
0 == '0' // true, because PHP casted both sides to numbers

// triple equals returns true only when type and value match
0 === '0' // false

FYI, From the PHP manual:

String conversion to numbers

When a string is evaluated in a numeric context, the resulting value and type are determined as follows.

The string will be evaluated as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will be evaluated as an integer.

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

Sign up to request clarification or add additional context in comments.

2 Comments

But why in python "a"==0 is false?
Python is not C. Unlike C, Python supports equality testing between arbitrary types. There is no 'how' here, strings don't support equality testing to integers, integers don't support equality testing to strings. So Python falls back to the default identity test behavior, but the objects are not the same object, so the result is False.
1

The php7 docs are explaining all cases here. Also exaclty your example.

var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("10" == "1e1"); // 10 == 10 -> true
var_dump(100 == "1e2"); // 100 == 100 -> true

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.