Is it possible to get values from inside a function and use those outside of the function?
Here is my code:
<?php
function cart() {
foreach($_SESSION as $name => $value){
if ($value>0) {
if (substr($name, 0, 5)=='cart_') {
$id = substr($name, 5, (strlen($name)-5));
$get = mysql_query('SELECT id, name, price FROM products WHERE id='.mysql_real_escape_string((int)$id));
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price']*$value;
echo $get_row['name'].' x '.$value.' @ £'.number_format($get_row['price'], 2).' = £'.number_format($sub, 2).'<a href="cart.php?remove='.$id.'">[-]</a> <a href="cart.php?add='.$id.'">[+]</a> <a href="cart.php?delete='.$id.'">[Delete]</a><br />';
}
}
$total += $sub ;
}
}
}
?>
Now my question is how can I get the value of $total? I want to use that value outside of the function. I have 2 functions 1 cart and 1 discount.
I tried return $total; (inside of function)
For example
$final = cart () - discount ();
echo $final;
It echos out both function, but code which is inside of function doesn't do any mathematical operation.
You need to "return" the value. See the entry in the PHP manual for this. Basically, return means "exit this function now". Optionally, you can also provide some data that the function can return.
Just use the return statement:
<?php
function cart()
{
foreach ($_SESSION as $name => $value) {
if ($value > 0) {
if (substr($name, 0, 5) == 'cart_') {
$id = substr($name, 5, (strlen($name) - 5));
$get = mysql_query('SELECT id, name, price FROM products WHERE id=' . mysql_real_escape_string((int)$id));
while ($get_row = mysql_fetch_assoc($get)) {
$sub = $get_row['price'] * $value;
echo $get_row['name'] . ' x ' . $value . ' @ £' . number_format($get_row['price'], 2) . ' = £' . number_format($sub, 2) . '<a href="cart.php?remove=' . $id . '">[-]</a> <a href="cart.php?add=' . $id . '">[+]</a> <a href="cart.php?delete=' . $id . '">[Delete]</a><br />';
}
}
$total += $sub;
}
}
return $total;
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With