0

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.

1
  • 3
    using global is not a recommended practice, you could pass the values to the function just as you pass it $lines Commented Feb 14, 2012 at 19:55

2 Answers 2

8

You should move global inside the function.

function printQuestions($lines){
    global $questions;
    // ...

The global keyword brings a global variable into local scope, so you can operate on it. If you don't use global in the printQuestions() function to bring the global $questions variable in the scope of the function, then $questions will be local and will be a different variable than the global one you're looking for.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use global variables in PHP as $GLOBALS["foo"] so in your case inside the function replace $questions with $GLOBALS["questions"] and everything should work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.