a1ias Posted June 22, 2006 Share Posted June 22, 2006 A fairly simple question (I hope) about variable scope.The following script, I would have expected, would insert "putmein" into the array named $myarray each time it was clicked on. The result of clicking 3 times, I thought would be an output of:[!--coloro:blue--][span style=\"color:blue\"][!--/coloro--]Array ( [0] => putmein, [1] => putmein, [2] => putmein )[!--colorc--][/span][!--/colorc--][code]<?phpif(isset($_GET[id])) { $id = $_GET[id]; $myarray[] = $id;}echo "<a href=".$_SERVER[PHP_SELF]."?id=putmein>click</a><br />";print_r($myarray);?>[/code]Unfortunately, as there is an issue with scope I assume? the result is:[!--coloro:blue--][span style=\"color:blue\"][!--/coloro--]Array ( [0] => putmein)[!--colorc--][/span][!--/colorc--]To be able to get the result I expected, I have to make the following adjustment to the code:[code]<?phpsession_start();if(isset($_GET[id])) { $id = $_GET[id]; $_SESSION[myarray][] = $id;}echo "<a href=".$_SERVER[PHP_SELF]."?id=putmein>click</a><br />";print_r($_SESSION[myarray]);?>[/code]What I would like to know, is it possible to get the desired result without reverting to using $_SESSION(s).I have tried declaring $myarray as a global variable at the beginning of the script but it has no effect at all.Your advice is welcomed :)Regards Quote Link to comment https://forums.phpfreaks.com/topic/12672-beginner-help-with-variable-scope/ Share on other sites More sharing options...
Eric_Ryk Posted June 22, 2006 Share Posted June 22, 2006 Global means that it works inside and outside of functions. This does not mean that it stored over different pages. After each page load every variable is cleared other than $_SESSION. Quote Link to comment https://forums.phpfreaks.com/topic/12672-beginner-help-with-variable-scope/#findComment-48598 Share on other sites More sharing options...
a1ias Posted June 22, 2006 Author Share Posted June 22, 2006 Many thanks for that, completely understand now.The "putmein" will be replaced with an item listed in a database, and each time the user clicks the item id it is added to the array and displayed in a shopping cart which will need to be refreshed after each click, hence the need for the page refresh.I guess sticking with the $_SESSION makes sense now then :) Quote Link to comment https://forums.phpfreaks.com/topic/12672-beginner-help-with-variable-scope/#findComment-48600 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.