0

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?

1
  • aren't you getting an error? isn't that array defined outside the scope of that function? Commented Aug 19, 2010 at 18:00

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.