Reputation: 85
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.
Upvotes: 3
Views: 5900
Reputation: 961
Your can use global scope. I.e.
$s = 1;
function eee()
{
global $s;
$s++;
}
echo $s;
Your can got var/return var... if your need return more that 1 value - use array
function eee( $s)
{
return $s++;
}
eee($s=1);
echo $s;
Prefer 2'd. Cause global scope operationing - may cause problems, when app become's large.
Upvotes: 0
Reputation: 76955
If you put return $total
at the very end of the function (right before the last curly brace), you should be able to use the result.
Upvotes: 0
Reputation: 237905
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;
}
?>
Upvotes: 3