Jump to content


Photo

Beginner help with Variable scope


  • Please log in to reply
2 replies to this topic

#1 a1ias

a1ias
  • Members
  • PipPip
  • Member
  • 17 posts

Posted 22 June 2006 - 08:30 PM

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

<?php

if(isset($_GET[id])) {

    $id = $_GET[id];
    $myarray[] = $id;
}


echo "<a href=".$_SERVER[PHP_SELF]."?id=putmein>click</a><br />";


print_r($myarray);

?>

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:

<?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]);

?>

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

#2 Eric_Ryk

Eric_Ryk
  • Members
  • PipPipPip
  • Advanced Member
  • 104 posts

Posted 22 June 2006 - 08:32 PM

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.

#3 a1ias

a1ias
  • Members
  • PipPip
  • Member
  • 17 posts

Posted 22 June 2006 - 08:39 PM

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 :)




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users