joomador Posted November 16, 2010 Share Posted November 16, 2010 Hi guys! I am trying to understand why the final value of $m equals 40 in the following code <?php $i = 29; $j = 11; $m = 10; $j = ($j - 4) / 2; $m += $j * 10; echo "m = ".$m."<br>"; //Equals 40 ?> Can anyone explain me please? I feel very confused right now. Link to comment https://forums.phpfreaks.com/topic/218799-help-with-operators/ Share on other sites More sharing options...
jcbones Posted November 16, 2010 Share Posted November 16, 2010 <?php $i = 29; $j = 11; $m = 10; $j = ($j - 4) / 2; //11 - 4 = 7 divided by 2 = 3.5 ($j is now 3.5) $m += $j * 10; //3.5 multiply by 10 = 35 plus 10 = 45 ($m is now 45) echo "m = ".$m."<br>"; //m = 45 ?> m = 45 not 40. Link to comment https://forums.phpfreaks.com/topic/218799-help-with-operators/#findComment-1134755 Share on other sites More sharing options...
btherl Posted November 16, 2010 Share Posted November 16, 2010 It would be 40 if the division was integer division. But php doesn't use integer division. From the manual: There is no integer division operator in PHP. 1/2 yields the float 0.5. The value can be casted to an integer to round it downwards, or the round() function provides finer control over rounding. Link to comment https://forums.phpfreaks.com/topic/218799-help-with-operators/#findComment-1134758 Share on other sites More sharing options...
joomador Posted November 16, 2010 Author Share Posted November 16, 2010 Thanks for the quick response guys! When I run the code it gives me 40 as the result. This is the whole code <?php $i = 29; $j = 11; $m = 10; $k = ($i++) + ($j--); echo "k = ".$k."<br>"; $j = ($j - 4) / 2; $m += $j * 10; echo "m = ".$m."<br>"; ?> Link to comment https://forums.phpfreaks.com/topic/218799-help-with-operators/#findComment-1134765 Share on other sites More sharing options...
harristweed Posted November 16, 2010 Share Posted November 16, 2010 Because j is now 10 not 11 altered here: ($k = ($i++) + ($j--) Link to comment https://forums.phpfreaks.com/topic/218799-help-with-operators/#findComment-1134767 Share on other sites More sharing options...
joomador Posted November 16, 2010 Author Share Posted November 16, 2010 Never expected to have answers so fast, you guys are great. Thank you! Link to comment https://forums.phpfreaks.com/topic/218799-help-with-operators/#findComment-1134769 Share on other sites More sharing options...
btherl Posted November 16, 2010 Share Posted November 16, 2010 Oh, it's totally unrelated to integer division then Just a coincidence. Link to comment https://forums.phpfreaks.com/topic/218799-help-with-operators/#findComment-1134774 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.