so I have a function set up, and I want to use one of the variables inside of the function to multiply with another variable stated outside of the function. <?php $var2 = $row_equipment['cost']; function() { $var1 = 4; } $var3 = $var1*$var2; echo $var3; ?> Code (markup): The problem is that I can echo var 1 inside of the function, but not var 2, and I can echo var 2 outside the function, not inside. thanks.
$var = 4; function foo($var) { $var2 = 5; $myMath = $var2 + $var; return $myMath; } echo foo($var); // displays 9 PHP: This is what you are trying to do I think. <?php $var2 = $row_equipment['cost']; function($var) { $var1 = 4; $var3 = $var1*$var; return $var3; } echo var($var2); ?> PHP:
The problem you're running into is that of scope - a variable declared outside of a function isn't available inside of a function and vice versa. This is because functions are designed to help you break down a larger script into smaller pieces... In order to communicate between the larger script and the function, you need to pass the variables back and forth. When you define the function, you can include any number of $vars inside the parentheses. You then call the function and place the variables inside the parentheses that you want to send. function foo($bar) { // Whatever value you "pass" into the function is saved in $bar } $x = 10; foo($x); // This sends $x, 10, to the function Code (php): In order for the function to talk back, you need to return a value. Whatever you place after 'return' will be sent back to your script - where you can save it or echo it. function foo($bar) { return $bar + 1; } echo foo(5); // This will echo 6 Code (php): So you need to re-write your function to include parameters (the variables inside the parentheses) and a return value. - Walkere
Use global keyword for accessing global variables inside the function: <?php $var2 = $row_equipment['cost']; function echovar() { global $var2; echo $var2; } echovar(); ?> PHP:
Don't use global, it is unneccessary anymore (unless working with large arrays of data, then you can get away with it). Pass arguments like mentioned above and return variables from the function in order to access them from within/without. Also, by globaling variables, you can run into security issues.