php中的变量范围

I'm into an issue, while running alertError(), it seems to be fine and there is an access for $errors, but while running showErrors(), it tells me that the variable is underfined. "Undefined variable: errors in"

$errors = array();

function alertError($error){
    $errors[] = $error;
    echo $errors[count($errors)-1];
}

function showErrors(){
        echo "<html>
                <head>
                    <title>Error occurred!</title>
                </head>
                <body>";
                foreach($errors as $error){
                    echo $error."<br>";
                }
        echo "
                </body>
             </html>";
    die();
}

Why does alertError() seems to know that $errors is defined, and showErrors() is having trouble accessing him?

add this line at the first line of showErrors()

global $errors;

this will give u access to the global $errors you declared above the functions

Update

As mantioned buy Mr. Alien and Neil Neyman in the comments - its a bed practice.. If you are going to program some php for more complex system - you should understand the OOP concept as shown in their links and comments.

Good Luck !

Pass errors to showErrors()

function showErrors($errors){
   ...
}

You may need your code like this

$errors = alertError($error);
showErrors($errors);

function alertError($error){
    $errors[] = $error;
    echo $errors[count($errors)-1];
    return $errors;
}

function showErrors($errors){
        echo "<html>
                <head>
                    <title>Error occurred!</title>
                </head>
                <body>";
                foreach($errors as $error){
                    echo $error."<br>";
                }
        echo "
                </body>
             </html>";
    die();
}

When function 'alertError()' runs it doesn't know anything about global variable $errors. It create new variable $errors every time. So it works correctly but not so as you want. In showErrors this variable is not declared so you get a notice. You can use statement global $errors in each function but it's a bad practice.