Mastering PHP Math: Solving a Tricky Example in a Tutorial

  • Context: Undergrad 
  • Thread starter Thread starter simy202
  • Start date Start date
  • Tags Tags
    Php
Click For Summary
SUMMARY

The forum discussion centers on a PHP math example that calculates the expression "((1 + 2 + $var1) * $var2) / 2 - 5". The user encounters confusion regarding the output, which is "7", while expecting a different result from the division of 24 by -3. The issue arises from the order of operations in PHP, where the division is performed after the subtraction, leading to the correct output. The final calculation clarifies that using parentheses around the denominator resolves the confusion.

PREREQUISITES
  • Understanding of PHP syntax and variables
  • Familiarity with mathematical operations in programming
  • Knowledge of operator precedence in PHP
  • Basic debugging skills in PHP
NEXT STEPS
  • Learn about PHP operator precedence and how it affects calculations
  • Explore the use of parentheses in mathematical expressions in PHP
  • Investigate PHP debugging techniques to troubleshoot similar issues
  • Review PHP documentation on arithmetic operations for deeper insights
USEFUL FOR

PHP developers, programmers learning arithmetic operations in PHP, and anyone troubleshooting mathematical expressions in their code.

simy202
Messages
1
Reaction score
0
I'm going through a php tutorial right now and this math example below is driving me nuts. The exmaple was "((1 + 2 + $var1) * $var2) / 2 - 5", and all the rest of the code below is just me trying to figure it out.

The answer ends up being "7", but to me it looks like PHP is sayding "24 / -3 = 7" when it should be "24 / -3 = -8". What am I missing in this http://www.phpkode.com/scripts/category/php-math/" issue?? Thanks!

PHP:
<?php
$var1 = 3;
$var2 = 4;
?>
    $var1 = 3;<br />
        $var2 = 4;<br /><br />
       <br />
       <h1> ((1  + 2 + $var1) * $var2) / 2 - 5 = <?php echo((1  + 2 + $var1) * $var2) / 2 - 5; ?><br /> </h1>
    <hr />
    <br />
    <br />
    LEFT SIDE:<br />
    (1  + 2 + $var1) * $var2 =  <?php echo ((1  + 2 + $var1) * $var2); ?><br />
<br />
RIGHT SIDE:<br />
2 - 5 =   <?php echo 2 - 5; ?><br />
    <br />
    24 / -3 SHOULD BE:
    <h1>24 / -3 = <?php echo 24 / -3; ?><br /></h1>

That spits out:

$var1 = 3;
$var2 = 4;

((1 + 2 + $var1) * $var2) / 2 - 5 = 7

LEFT SIDE:
(1 + 2 + $var1) * $var2 = 24

RIGHT SIDE:
2 - 5 = -3

24 / -3 SHOULD BE:
24 / -3 = -8
 
Last edited by a moderator:
Mathematics news on Phys.org
Try:
<?php echo((1 + 2 + $var1) * $var2) / (2 - 5); ?>
 

Similar threads

  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 59 ·
2
Replies
59
Views
231K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 55 ·
2
Replies
55
Views
7K
Replies
1
Views
4K
  • · Replies 68 ·
3
Replies
68
Views
13K
  • · Replies 8 ·
Replies
8
Views
3K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K