0
<?php
    $test = "-3,-13";
    if ($test == -3) {
        echo "yay";
    } else {
        echo "nay";
    }

?>

why it always runs through if condition and not going in else condition? I am new to php so do not know what's going on here.

James Z
  • 12,209
  • 10
  • 24
  • 44
  • 4
    You are comparing a string value to a number, so the string needs to be converted into a number - and the result of that simply is `-3`. https://www.php.net/manual/en/language.types.type-juggling.php – CBroe Feb 28 '20 at 13:00
  • 3
    Does this answer your question? [Comparing String to Integer gives strange results](https://stackoverflow.com/questions/672040/comparing-string-to-integer-gives-strange-results) – iainn Feb 28 '20 at 13:01
  • `==` conversion , `===` no conversion... – MUY Belgium Feb 28 '20 at 13:59

2 Answers2

1

The string is converted into an integer "-3, 46, blala" -> -3 , then the condition is evaluated.

Use the === operator to avoid conversion.

Most of the time, you do not want to let php do the conversion in your place (security problem). Rather, the request is refused.

MUY Belgium
  • 2,330
  • 4
  • 30
  • 46
0

As PHP documentation says

Example     Name    Result
$a == $b    Equal   TRUE if $a is equal to $b after type juggling.
$a === $b   Identical   TRUE if $a is equal to $b, and they are of the same type.

When we compare a number with a string, the string is converted to a number and the comparison performed numerically.

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

https://www.php.net/manual/en/language.operators.comparison.php

Leonardo
  • 791
  • 1
  • 5
  • 21