"if" does not match the condition

Asked

Viewed 293 times

-2

I’m trying to apply a if in my code, but it’s coming wrong:

<?php     
echo $usu_id . "<br />";
echo $centraliz . "<br />";
echo $marca . "<br />";

if($centraliz = "S"){

echo "É centralizada";

} else {

echo "Não é centralizada";

}
?>

But the result is coming like this:

erro

  • 4

    That’s because you did an assignment within the if, using the operator =. The correct would be two equal signs to compare, ==.

2 answers

10

Change to

if ($centraliz == "S") {

I put in the Github for future reference.

The operator = is of attribution, the == is by comparison. So you’re stating that centralizada is S and of course a statement is always true. In some situations (not in this) it is even necessary to use the === to ensure that the two operands are of the same type.

1


A practical example for better understanding:

<?php   
$variavel = 'true';

if($variavel == "true"){
   echo "1";
}
if($variavel == true){
   echo "2";
}
if($variavel === true){
   echo "3";
}
if($variavel = true){
   echo "4";
}
echo $variavel;

The values that will be shown on the screen: 1, 2, 4 and 1

($variable == "true") = True because it’s the same string.
($variable == true) = True because true equals true.
($variable === true) = False because true is true, but types are different, one is a string and the other is boolean.
($variable = true) = true since it is a simple value assignment, this case will only be false if the assignment fails, usually the false return happens when the value for comparison comes from a function, the function can return something that is impossible to assign.
And the value 1 of the end is the result of the "$variable" since after the ($variable = true) its value passed to true because of the assignment and when showing on the screen it shows 1 that is true for php, if you do so 'echo true;' the result on the screen will be 1 too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.