-1

why php code does not go in show error or check_data function

<?php
$error_array = array();
if (isset($_REQUEST["welcome_already_seen"])) {
    check_data();
    if (count($error_array) != 0) {
        show_error();
        show_welcome();
    } else {
        handle_data();
    }
} else {
    show_welcome();
}

function show_welcome()
{
    echo "<form method='post'>
        <input type='text' name='flavor'>
        <input type='submit' value='submit'>
        <input type='hidden' name='welcome_already_seen' value='already_seen'>
        </form>";
}

function check_data()
{
    if ($_REQUEST["flavor"] == "") {
        $error_array[] = "<div style='color:red'>please enter flavor</div>";
    }
}

function show_error()
{
    global $error_array;
    foreach ($error_array as $err) {
        echo $err, "<br>";
    }
}

function handle_data()
{
    echo "flavor =";
    echo $_REQUEST["flavor"];
}

?>

why php code does not go in show error or check_data function is there any solution and tell what the problem within the code

Alexander Yancharuk
  • 13,817
  • 5
  • 55
  • 55
Love Trivedi
  • 3,899
  • 3
  • 20
  • 26

2 Answers2

1

It does go to check_data function but you are using $error_array in local scope hence global array is not populated.

You should make it global in your function - like that:

    function check_data(){
        global $error_array;

        if($_REQUEST["flavor"] == ""){
            $error_array[] = "<div style='color:red'>please enter flavor</div>";
        }
    }
1

You missed global $error_array in your function check_data. It is going to check_data() but setting a local variable so the global $error_array is always empty.

 function check_data(){     
    global $error_array;
    if($_REQUEST["flavor"] == ""){          
        $error_array[] = "<div style='color:red'>please enter flavor</div>";
    }
  }
Konsole
  • 3,447
  • 3
  • 29
  • 39