05 09

Example of assignment operators in php

example of assignment operators in php

In response to mathiasrav at gmail dot com:

The reason for that behavior is the parentheses. From the description:

"Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18."

So the order of operations says that even though the equality operator has higher precedence, the parentheses in your statement force the assignment operator to a higher precedence than the equality operator.

That said, it still doesn't work the way you expect it to. Neither way works, for these reasons:
<?php
if ( $a != ($a = $b) )
?>

Order of operations says to do the parentheses first. So you end up with:
<?php
$a
= $b;
if (
$a != $a )
?>

Which is obviously going to be false. Without the parentheses:
<?php
if ( $a != $a = $b )
?>

Order of operations says to do the inequality first, then the assignment, so you have:
<?php
if ( $a != $a );
$a = $b;
?>

Which again is not what you expected, and again will always be false. But because you are only working with values of 0 and 1, you can make use of the XOR operator:

<?php
if ( $a ^= $b )
?>

This will only be true if 1) $a is 0 and $b is 1, or 2) $a is 1 and $b is 0. That is precisely what you wanted, and it even does the assignment the way you expected it to.

<?php
foreach ($ourstring as $c) {
if (
$bold ^= $c['bold']) $resstring .= bold;
if (
$underline ^= $c['underline']) $resstring .= underline;
$resstring .= $c[0];
}
?>

That code now works and produces the output you expected.

Tutorials - Example Point Assignment PHP Operators

Assignment Operators : PHP - PHP Tutorials - c4learn.com

example of assignment operators in php PHP: Operators - Manual

example of assignment operators in php PHP Tutorial - Operators - Tizag

Comments

  1. Qegemelifofim

    Lois Lerner and John Kosiken R just 2 Operators w/were victimized by. The Tip of the Iceberg. and

  2. Qivujaroyotaf

    Come to think of it, I also trust used car salesmen and 3 card monte operators more than the President.

  3. Ziviwoyiyayo

    Estate Agents are a professional that people will remember in the future like we think of Lamp Lighters or Switchboard Operators

  4. Woholowa

    In 2016, there were 271, 935 farm operators with an average age of 55.0 years.

  5. Murozakakag

    Taking small bites of big data Operators pick the right tools to manage food cost

  6. Ceroqacu

    US fantasy operators push the boundaries of legal sports betting

  7. Yoqozaqes

    : files misdemeanor charges against operators of after-hours club where resident was shot and killed.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>