Andy
Andy

Reputation: 3170

Pulling values from an array in separate file

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?

Upvotes: 0

Views: 162

Answers (1)

Daniel Vandersluis
Daniel Vandersluis

Reputation: 94123

$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!)

Upvotes: 3

Related Questions