user2670708
user2670708

Reputation: 143

What is my error in the very simple php?

i make a very simple php to check a data, but it not works.

<?php
    $ngl="G";
    if ($parsed[0][4]="0") {
        $ngl="NG";
    }
    if ($parsed[0][5]="0") {
        $ngl="NG";
    }
?>

and the output of the

<?php echo $ngl; ?>

is always

G

But I know that $parsed[0][4] and $parsed[0][5] is 0. The problem is that the output is G and not NG! I also tried to remove $ngl="G"; but then the output is nothing.

What do I have to repair?

i just use = but == its the correct. thx all.

Upvotes: 0

Views: 81

Answers (5)

MDEV
MDEV

Reputation: 10838

You're assigning (=) a value instead of comparing (== or ===)

<?php
$ngl = "G";
if($parsed[0][4] == "0")
{
    $ngl = "NG";
}
if($parsed[0][5] == "0")
{
    $ngl = "NG";
}
?>

Explanation:

When you put an assignment like $parsed[0][4]="0" in an if statement, the if will evaluate the "0" to false. The reason it evaluates just the "0" is because the line $parsed[0][4]="0" (any assignment) returns the right hand side of the operation (the "0")

== vs === : php.net - Comparison Operators

== is a loose comparison which doesn't compare the type. ie "2" == 2 is true (even though one is a string and the other is an integer)

=== is a strict comparison, comparing types as well as values. ie "2" === 2 is false

The if statement uses the former (loose) comparison on your "0", and of course 0 is the false value in binary (0 and 1), so 0 == false and "0" == false both evaluate to true - however, 0 === false would return false as 0 is an integer, whereas false is a boolean.

Upvotes: 1

K&#225;roly Nagy
K&#225;roly Nagy

Reputation: 1754

This line is not checking if $parsed[0][4] is zero. It makes it zero.

if ($parsed[0][4]="0") {

Change it to

if ($parsed[0][4]=="0") {

Upvotes: 0

jh314
jh314

Reputation: 27792

You should use == rather than =:

<?php
    $ngl="G";
    if ($parsed[0][4]=="0") {
        $ngl="NG";
    }
    if ($parsed[0][5]=="0") {
        $ngl="NG";
    }
?>

The reason is that the = is the assignment operator, while the == is the comparison operator (which is the one you want).

$parsed[0][4]=="0" will evaluate to 0, which is false, so $ngl will not be changed. The same thing happens with $parsed[0][5]=="0"

Upvotes: 0

esqew
esqew

Reputation: 44698

You use = to set variables. You use == to compare.

<?php
    $ngl="G";
    if ($parsed[0][4]=="0") {
        $ngl="NG";
    }
    if ($parsed[0][5]=="0") {
        $ngl="NG";
    }
?>

Upvotes: 0

Kevin Lynch
Kevin Lynch

Reputation: 24703

Use == not = when checking

<?php
$ngl="G";
if ($parsed[0][4]=="0") {
$ngl="NG";
}
if ($parsed[0][5]=="0") {
$ngl="NG";
}
?>

Upvotes: 0

Related Questions