Consider the following function which fills an array with strings(questions):
global $questions;
function printQuestions($lines){
$count = 1;
foreach ($lines as $line_num => $line) {
if($line_num%3 == 1){
echo 'Question '.$count.':'.'<br/>'.'<input type="text" value="' . $line . '" class="tcs"/>'.'<br/>';
$count++;
$questions[] = $line;
}
}
}
The questions array is defined as global but it’s not accessible outside the function. The following code block located at the bottom of the page returns nothing:
<?php
if(isset($_POST['Submit'])){
foreach($questions as $qs)
echo $qs;
}
?>
I know I could use session variables but I’m interested in this particular problem regarding global variables. Any help is greatly appreciated.
You should move
globalinside the function.The
globalkeyword brings a global variable into local scope, so you can operate on it. If you don’t useglobalin theprintQuestions()function to bring the global$questionsvariable in the scope of the function, then$questionswill be local and will be a different variable than the global one you’re looking for.