开发者

My PHP Function isn't working

开发者 https://www.devze.com 2022-12-08 13:09 出处:网络
I\'m 开发者_Python百科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?

I'm 开发者_Python百科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);


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];
}


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

global $bookLocations;


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];


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).


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];
}


$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.

0

精彩评论

暂无评论...
验证码 换一张
取 消