On Fri, Oct 2, 2009 at 17:28, Daevid Vincent <dae...@daevid.com> wrote:
>
> Personally I've never (in almost 20 years) done an assignment like "$foo =
> $foo++" as I always use just "$foo++" or "$foo += 1" or something, hence the
> reason today is the day a co-worker stumbled upon this and was as confused
> as I was until I figured it out.

    And that's exactly the point: why would you assign this variable
to another in the first place?  It's just using up resources and
creating more overhead in the application.  The reason it exists is
for processing, really, not assigning; and the ability to do it before
or after is appropriate for certain conditions.  However, keep in mind
that you don't even need to do anything with the variable to increment
it:

<?php
$n = 1;
$n++;
echo $n."\n"; // 2
?>

    The $var++ vs. ++$var (or, conversely, $var-- vs. --$var)
comparison isn't best described by the most commonly-used incrementing
scenario:

<?php
$a = array('foo' => 'bar', 'apple' => 'red', 'lime' => 'green', 'wife'
=> 'pain in ass', 'lemon' => 'yellow');
for($i=0;$i<count($a);$i++) {
    // ....
}
?>

    .... but rather by something just slightly more advanced:

<?php
$num = file_get_contents('visitcount.txt');
if(isset($_GET['countme'])) {
    echo "You are visitor #".++$num."<br />\n";
    file_put_contents($num);
}
?>

    If you were to use $num++, it would echo out the current number,
THEN increment the value.  In this example, it increments the value,
THEN echoes it out.  The placement of the signs (plus or minus) is the
giveaway: if it's before the variable, it's modified before being
processed.  If it's after, then it's evaluated immediately after the
variable is processed.

-- 
</Daniel P. Brown>
daniel.br...@parasane.net || danbr...@php.net
http://www.parasane.net/ || http://www.pilotpig.net/
Check out our great hosting and dedicated server deals at
http://twitter.com/pilotpig

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to