I'm writing a script that will select a random word from among words in an input file, multiple times. Now calling file() multiple times seems inefficient, so I'm thinking of having a global array for the words from the file and a function that will load the file into the array (called before selecting random words). Why doesn't it work?
global $words;
function init_words($file)
{
$words = file($file);
$count = count($words);
echo "$count words<br>\n"; // "3 words"
}
init_words("/foo/bar");
$count = count($words);
echo "$count words<br>\n"; // "0 words"
You need to declare $words global within the function itself. See:
$words = '';
function init_words($file)
{
global $words;
$words = file($file);
$count = count($words);
echo "$count words<br>\n"; // "3 words"
}
I suggest you review the variable scope chapter in the PHP manual.
As an aside I would never write this code in this way. Avoid globals unless they are absolutely necessary.
I would write your code this way to avoid this problem:
function init_words($file)
{
$words = file($file);
$count = count($words);
echo "$count words<br>\n"; // "3 words"
return $words;
}
$words = init_words("/foo/bar");
$count = count($words);
echo "$count words<br>\n"; // "3 words"
Please see the returning values chapter in the PHP manual for more information on this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With