I've been using php for a while now, but have just started using functions a lot. I am trying to bring a variable that is inside of a function outside of it. here is the function... <?php function check_sn($cat_num,$sn,$i){ $sn_req = mysql_query("SELECT `ser_no_req` FROM `categories` WHERE `cat_no`='$cat_num'") or die(mysql_error()); $sn_req_res = mysql_fetch_assoc($sn_req); if ('y' == $sn_req_res['ser_no_req']){ for($i=$_POST['ship' . $cat_num];$i>0;$i--){ $sn[$cat_num.$i] = $_POST['sn' . $cat_num . $i]; }; }; print_r($sn); };?> PHP: When it runs through that, it prints $sn, but when it goes out of the function it won'g print $sn. How can I correct this? Thanks in advance! Nathan
Hello, You need to make the variable global. Demo code: <? function dosomething(){ global $variable; $variable = 'test'; echo "$variable\n"; } dosomething(); echo $variable; ?> PHP: Output: test test Code (markup): Jay
or return the variable from the function, it's cleaner and doesn't global it. function check_sn($cat_num,$sn,$i){ $sn_req = mysql_query("SELECT `ser_no_req` FROM `categories` WHERE `cat_no`='$cat_num'") or die(mysql_error()); $sn_req_res = mysql_fetch_assoc($sn_req); if ('y' == $sn_req_res['ser_no_req']){ for($i=$_POST['ship' . $cat_num];$i>0;$i--){ $sn[$cat_num.$i] = $_POST['sn' . $cat_num . $i]; }; }; print_r($sn); return $sn; }; $out = check_sn($data1,$data2,$data3) print_r($out); ?> PHP:
Except if you need to take multiple variables out, or when the variables you require depend on the input of the process. Return is easier for one variable, and Global is easy for multiple variables (rather than returning array($var1, $var2, $varetc)). Jay
... or pass the initial parameters by reference instead of by value. That way, when you change the value in the function, that change is 'persistent' in the original value passed in to the function.