why this happens????

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
yagoda
Forum Newbie
Posts: 1
Joined: Mon Nov 25, 2002 8:14 am
Location: bulgaria
Contact:

why this happens????

Post by yagoda »

Hi all! please try this and see the result:

<?php
$a = 7; echo $a = $a + $a++;
//the result is 14;

$a = 7; $b = &$a; echo $a = $a + $a++;
//the result is 15;
?>
User avatar
BDKR
DevNet Resident
Posts: 1207
Joined: Sat Jun 08, 2002 1:24 pm
Location: Florida
Contact:

Post by BDKR »

Yeah, this is very strange. They should both equal 15. The behaviour of that first example is odd. I did the same thing in Perl and it worked fine.

Anybody have any other ideas?

Cheers,
BDKR
User avatar
BDKR
DevNet Resident
Posts: 1207
Joined: Sat Jun 08, 2002 1:24 pm
Location: Florida
Contact:

Post by BDKR »

This is curious too.

Code: Select all

$a = 7; 
echo $a = $a + ++$a;
echo "\n";
echo "\$a = $a\n";
//the result should be 16;
Does this make sense to anybody else? Something is severly whacked in Denmark!

Cheers,
BDKR
User avatar
BDKR
DevNet Resident
Posts: 1207
Joined: Sat Jun 08, 2002 1:24 pm
Location: Florida
Contact:

Post by BDKR »

OK,

I found what does work, but the other posted examples should work as well. The logic is just as correct as what is below.

Code: Select all

&lt;?php

$a = 7; 
echo $a = $a++ + $a;
echo "&lt;br&gt;";
echo "\$a = $a&lt;br&gt;";
//the result is 15;

$a = 7; 
echo $a = ++$a + $a;
echo "&lt;br&gt;";
echo "\$a = $a&lt;br&gt;"; 
//the result is 16;

?&gt;
Now it works as it should, but there must be something amiss in the scripting engine that the other logic doesn't work.

Cheers,
BDKR
User avatar
PaTTeR
Forum Commoner
Posts: 56
Joined: Wed Jul 10, 2002 7:39 am
Location: Bulgaria
Contact:

Post by PaTTeR »

Code: Select all

$a=7;
echo $a += $a++;
This is 15.
User avatar
BigE
Site Admin
Posts: 139
Joined: Fri Apr 19, 2002 9:49 am
Location: Missouri, USA
Contact:

Post by BigE »

wow, ok... a little explination is due here I think. $a++ will return 7 and then incrament, so the $a = $a + $a++; should be 14. ++$a incraments then returns the number, so $a = $a + ++$a; would be 15. Why when you reference $a using $b = &$a; then do $a = $a + $a++; returns 15, I'm not sure. Might check in the manual on that one.
User avatar
BigE
Site Admin
Posts: 139
Joined: Fri Apr 19, 2002 9:49 am
Location: Missouri, USA
Contact:

Post by BigE »

OK, I've figgured it out. The reason that after you reference $a that $a + $a++ returns 15 is because when ++ takes precidence. Check out http://www.php.net/manual/sv/language.o ... precedence for more information. Hope that helps.
Post Reply