Mathmatical Operators

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
dubs
Forum Commoner
Posts: 28
Joined: Tue Oct 12, 2004 4:55 pm

Mathmatical Operators

Post by dubs »

Code: Select all

<?php
$cart[$Product][0] = $cart[$Product][0] - $Qty;
?>
The above removes the value of $Qty from Qty index in my array. At the moment the operator is hardcoded but would prefer to pass in the operator via a url

I've tried this but get an error

$cart[$Product][0] = $cart[$Product][0] $Operator $Qty;
or
$cart[$Product][0] $Operator = $Qty;

Both give me errors, is there way of doing this in php :roll:
Tubbietoeter
Forum Contributor
Posts: 149
Joined: Fri Mar 14, 2003 2:41 am
Location: Germany

Post by Tubbietoeter »

Write yourself a function for this and evaluate $Operator within the function.
rehfeld
Forum Regular
Posts: 741
Joined: Mon Oct 18, 2004 8:14 pm

Post by rehfeld »

tip:

instead of writting

Code: Select all

<?php
$foo = $foo - $bar;
?>
you can do this type of stuff

Code: Select all

<?php
$foo -= $bar;
$foo += $bar;
$foo %= $bar;
$foo /= $bar;
?>
etc....


the only way to pass in the operator as a variable would be to use eval(), which is a bad bad thing to use usually. its slow, and has security issues. Much better would be to do this type of stuff:

Code: Select all

<?php
if ($operator === '+') {
    $foo += $bar;
} elseif ($operator === '-') {
    $foo -= $bar; 
} // etc....
?>

but in the end, using a class, or at least a set of functions, will be the best answer.

if you want a nice little shopping cart class i have one. Youll need to learn how to use classes.
dubs
Forum Commoner
Posts: 28
Joined: Tue Oct 12, 2004 4:55 pm

Post by dubs »

Cheer worked a treat
User avatar
mudkicker
Forum Contributor
Posts: 479
Joined: Wed Jul 09, 2003 6:11 pm
Location: Istanbul, TR
Contact:

Post by mudkicker »

you can change that if/elseif loop with a switch() loop, too.
Post Reply