Page 1 of 1

Mathmatical Operators

Posted: Thu Oct 21, 2004 5:22 am
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:

Posted: Thu Oct 21, 2004 6:14 am
by Tubbietoeter
Write yourself a function for this and evaluate $Operator within the function.

Posted: Thu Oct 21, 2004 5:42 pm
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.

Posted: Fri Oct 22, 2004 3:42 am
by dubs
Cheer worked a treat

Posted: Sun Oct 24, 2004 7:27 pm
by mudkicker
you can change that if/elseif loop with a switch() loop, too.