How do I fix “Undefined variable” error in PHP?

Today, I have started to learn PHP. And, I have created my first PHP file to test different variables. You can see my file as follows.

<?php
    $x = 5; // Global scope

    function myTest()
    {
        $y = 10; // Local scope
        echo "<p>Test variables inside the function:<p>";
        echo "Variable x is: $x";
        echo "<br>";
        echo "Variable y is: $y";
    }

    myTest();

    echo "<p>Test variables outside the function:<p>";
    echo "Variable x is: $x";
    echo "<br>";
    echo "Variable y is: $y";
?>

I have found the following errors when I have run this file in the browser.

Notice: Undefined variable: x in /opt/lampp/htdocs/anand/php/index.php on line 19

Notice: Undefined variable: y in /opt/lampp/htdocs/anand/php/index.php on line 29

How can I fix the issue regarding it?

Leave a Comment