Jump to content

Archived

This topic is now archived and is closed to further replies.

a1ias

Beginner help with Variable scope

Recommended Posts

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]
<?php

if(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]
<?php

session_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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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 :)

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.