Jump to content

Beginner help with Variable scope


a1ias

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.