Reputation: 14559
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
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
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
Reputation: 40675
Ok, there are two issues.
Your function doesn't know the array $bookLocations
, you need to pass it to your function like so:
function findfile($filenumber, $bookLocations)
You don't want to wrap your array key in quotes:
wrong: $bookLocations["$filenumber"];
right: $bookLocations[$filenumber];
Upvotes: 3
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
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
Reputation: 2642
i believe you may also need to declare the global variable in your function.
global $bookLocations;
Upvotes: 5