0

I want to make a function that change the value of global variable dynamically with a loop. i tried to to put 'global' behind the $$key but it throws error. is it possible to do that?

define('INPUT_FIELDS', array('fullname', 'phone', 'email')); // the input fields names that every form must have

$fullname = $phone = $email = "";

function isPostValid(){
    if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
        foreach ($_POST as $key => $value) {
            if( in_array($key, INPUT_FIELDS) ){// only if the key is exists in the inputs we chose
                $$key = checkInputsAndValidate($key);

                if(!$$key){// if the variable is null then break the loop and make change the variable to false
                    return false;
                    break;
                }
            }
        }//END foreach
        return true;
    }

    return false;
}

2
  • This answer help you? LINK Commented May 5, 2020 at 12:43
  • Are you perhaps thinking of the &$key syntax for referenced variables? If not then you would need to use global $key; as you enter your function to "expose" it. Commented May 5, 2020 at 12:48

1 Answer 1

1

Like Dave said in the comment, you have to use the global keyword to reference a global variable. But you should also try to make your code scalable for more possible variables (i.e. use an array).

I would suggest to change the function something like this:

<?php

define('INPUT_FIELDS', array('fullname', 'phone', 'email'));

/** create a global var that holds all form data **/
$FORM = array();
/** initialize $FORM based on defined input fields **/
foreach (INPUT_FIELDS as $key)
    $FORM[$key] = false;

function isPostValid(){
    /** access global variable $FORM **/
    global $FORM;

    /** verify POST request **/
    if ($_SERVER['REQUEST_METHOD'] !== 'POST')
        return false;

    /** check all FORM keys for POST values **/
    foreach($FORM as $key => $init_value) {

        /** How does checkInputsAndValidate() work in your code?
          * -> change here if necessary
          **/
        $new_value = isset($_POST[$key]) ? checkInputsAndValidate($key) : false;

        if (!$new_value)
            return false;

        $FORM[$key] = $new_value;
    }

    /** if all is OK, return true **/
    return true;

}

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

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.