Search the database and compare

-3

I have a simple code whose goal is to get the value of a field and make a comparison, if the value is zero, do one thing, otherwise make another.

In the meantime I must be missing something because it is not working as expected.

This was my attempt:

<?

$teste=$produto['fold'];

if($teste==0) {

?>

---

<?

} else {

?>

<a href="<?= $produto['fold']; ?>">Link</a>

<?

}

?>

With this code it enters both if and else . Where is my error?

    
asked by anonymous 17.12.2014 / 19:14

1 answer

1

The problem is with the cast stupid and nosy PHP.

Second the manual :

  

If you compare a number with a string or the comparison consists of numeric strings, then each string will be converted to a number and the comparison will occur numerically. [...] This conversion does not apply when the comparison is made with operators === or! == since this characterizes comparison by value and type.

That said, in your test:

if( $teste == 0 )

The left side is first interpreted as the variable it represents.

The right side, because a number "suggests" to the interpreter that the comparison should be numeric and thus the string that the variable represents, internally passes to be a number as well.

It's like this is being done:

if( (int) $teste == 0 )

And as a string can not be a number (obvious) the result of the conversion becomes zero and the rest is logical.

To solve this kind of subtle problem and difficult debugging use typed comparison as the manual says:

if( $teste === 0 )

And the link will be created.

Apart from this, I suggest that when you're generating HTML with PHP you'd prefer to use the syntax alternative of control structures because it is MUCH easier to understand the open-and-date tags:

<?php if( $produto['fold'] === 0 ) : ?>

---

<?php else : ?>

<a href="<?= $produto['fold']; ?>">Link</a>

<?php endif; ?>
    
23.12.2014 / 20:57