Casting type and comparison with Loose Operator "=="

I have a problem that baffles me. I have noticed this before, but still have not paid attention to it. I tried to write my own check for whole lines. I know is_numeric(), but this is not enough, because he considers it to be floatnumerical, and not just integersthat is_int(), which does not work with string numbers.

I did something like this


$var1 = 'string';
$var2 = '123'; 

var_dump( (int)$var1 == $var1);// boolean true 
var_dump((int)$var2 == $var2);// boolean true

 var_dump((int)$var1);//int 0
 var_dump($var1);//string 'string' (length=6)

As expected, the second dump of var outputs true, since I expect that when comparing php with an equal value, the strings and integer versions will be equal.

However, the first time I do not understand why this is so. I tried casting on booland it still gives me the same result.

I tried to assign cast var to a new variable and compare two, all the same result

- php?

*** . , int 0 string 'string'.

-, .

*** , , 0 == 'string' . ?

*** 2 . , .

+5
7

, . , cast 0, . , , , . - "" . ( , strcmp, -, .)

, , is_numeric, int , int .

if (is_numeric($value) && strcmp((int)$value, $value) == 0)
{
    // $value is an integer value represented as a string
}
+5

php.net http://php.net/manual/en/language.operators.comparison.php:

var_dump(0 == "a"); // 0 == 0 -> true

, , , int. ascii, ascii .

+2

, '=' b/c (A = B B = C = > A = C).

PHP "=="!

(int)$var1 == $var1

PHP 'string' 0 - .

== - 'string', integer → 0.

.

+2

, :

bool(true)
bool(true)
int(0)
string(6) "string"

:

  • , ==, PHP , , 100% - : if((int)$var1 == (int) $var1)
  • . 1), .
  • int(0), , , 0 .
  • string(6) "string" -
+2

, ===.

+1

: Twig, .

, SO, , .

TL; DR: . (= double equals) (=== triple equals)?

  • Twig template engine ( 2017-01-27T05: 12: 25)

  • YlohEnrohK twig
  • YlohEnrohK

  • (==) Twig?
  • ?

    {{ dump(0 == 'somekey') }}          ==> true
    {{ dump(0|lower == 'somekey') }}    ==> false
    

  • Twig === , PHP
  • Twig === same as
  • - PHP Twig.

.

+1

, int, .

function isIntegerNumeric($val) {
  return (
    is_int($val)
      || (
        !is_float($val)
          && is_numeric($val)
          && strpos($val, ".") === false
      )
  );
}

This is relatively fast and avoids string checking if it is not needed.

0
source

All Articles