tags:

views:

16

answers:

1

Hello, again. Right now I'm having issues with some pretty basic functionality in PHP. I have a web page which includes the following code:

  function laserOn()
  {
    $_SESSION['laser'] = TRUE;

    $num_victims = rand(2,125);
    $vic = rand(0, count($victims) - 1);

    print $num_victims." ".$victims[$vic]." have been vaporized!<br />";
  }

and a separate file, victims.php which i have require_once'd, that contains

$victims = array(
    1 => "chickens",
    2 => "horses",
    3 => "werewolves",
    4 => "zombies",
    5 => "vampires",
    6 => "cows"
);

The page, though, only displays the number and the string, not the array value. WHat am I doing wrong here?

+3  A: 

$victims does not appear to be within the scope of your function. In order to use a global variable within function scope, you need to declare it using the global keyword (see variable scope in the php.net docs).

function laserOn()
{
  global $victims;

  // ... rest of your function
}

Alternately, you could require the file that contains the array within the function, but this might not be desired (especially if the file defines functions of its own!)

Daniel Vandersluis
That was it, exactly. Thank you!
Andrew