waiwai933
waiwai933

Reputation: 14559

My PHP Function isn't working

I'm having trouble with the following code. What it should do is echo cats.php followed by example.php but it's not echoing the example.php. Any ideas why this might be happening?

$bookLocations = array(
    'example.php',
    'cats.php',
    'dogs.php',
    'fires.php',
    'monkeys.php',
    'birds.php',
);

echo $bookLocations[1];

function findfile($filenumber)
{
echo $bookLocations["$filenumber"];
}

findfile(0);

Upvotes: 0

Views: 361

Answers (6)

ftdysa
ftdysa

Reputation: 1242

Try changing,

echo $bookLocations["$filenumber"];

to:

echo $bookLocations[$filenumber];

Edit* To expand on Thomas's correct answer, instead of using global variables, you could change your method to:

function findfile($filenumber, $bookLocations)
{
    echo $bookLocations[$filenumber];
}

Upvotes: 6

Andrejs Cainikovs
Andrejs Cainikovs

Reputation: 28434

function findfile($filenumber)
{
  global $bookLocations;
  echo $bookLocations[$filenumber];
}

Good-style developers usually avoid global variables. Instead, pass the array to the function as the parameter:

function findfile($files, $filenum)
{
  echo $files[$filenum];
}

Upvotes: 1

markus
markus

Reputation: 40675

Ok, there are two issues.

Variable Scope

Your function doesn't know the array $bookLocations, you need to pass it to your function like so:

function findfile($filenumber, $bookLocations)

Array key

You don't want to wrap your array key in quotes:

wrong: $bookLocations["$filenumber"];
right: $bookLocations[$filenumber];

Upvotes: 3

easement
easement

Reputation: 6139

$bookLocations is out of scope for your function. If you echo $filenumber you will see that it's in scope because you passed it in by value. However, there is no reference to $bookoLocations.

You should pass in $bookLocations

declaration: function findfile($filenumber, $bookLocations){ call: findfile(1, $bookLocations);

You could also to declare $bookLocations as global, but globals should be avoided if possible.

Upvotes: 0

Mark Rushakoff
Mark Rushakoff

Reputation: 258158

The quotes in "$filenumber" turn your key into a string, when the keys to your array are all numbers. You are trying to access $bookLocations["1"] when in fact you want to access $bookLocations[1] -- that is to say, 1 is not the same as "1". Therefore, like others have said, you need to get rid of the quotation marks around the key (and check your variable scope too).

Upvotes: 1

thomas
thomas

Reputation: 2642

i believe you may also need to declare the global variable in your function.

global $bookLocations;

Upvotes: 5

Related Questions