3

I am trying to write a func to replace a large chunk of repetitive code:

$inputVals = array( $siteId, $siteName, $numHspaBbu, $numLteBbu, $extAlarmsTerminated, $cellLowPower );

    function updateVarVals( $inputVals ) { // assign values to $vars after Update button clicked      
      foreach( $inputVals as $val ) {
        if ( $_POST[ $val ] !== "" ) { // if $_POST value is not empty then assign to $var and corresponding $_SESSION value  
        $val = $_SESSION[ $val ] = $_POST[ $val ];
        } else { // re-assign $_SESSION value to $var
          $val = $_SESSION[ $val ];
        } // close IF
      } // close FOREACH
    } // close FUNC

    updateVarVals( $inputVals );

but no matter how I quote $val I keep getting:

Notice: Undefined index: <$val value> in C:\xampp\htdocs\database on line 145.

for every iteration of the loop. Why is PHP expecting variable values to be defined here?

4
  • 3
    Possible duplicate of PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" Commented Mar 20, 2017 at 9:11
  • Cau u share the more information about the variables that are being passed in $inputVals? Are these keys being used as key in your $_POST array? Commented Mar 20, 2017 at 9:15
  • did you validate your inputs to see if they are set and not empty? Commented Mar 20, 2017 at 9:15
  • @Masivuye Cokile: Inputs are initially set by SQLquery to DB on Retreive event and print_r( $inputVals ); proves it. Then if user alters one of the inputs and clicks update, JS code detects on(change) and sends change via ajax.php file, which I am now trying to use to update php vars accordingly: if ( empty( $_POST[ $val ] ) { then re-assign $_SESSION[ $val ] to $val, otherwise assign changed input value to $var & $_SESSION[ $val ]. And after Update event print_r( $inputVals ); again proves the changed values are assigned accordingly. Commented Mar 20, 2017 at 9:29

1 Answer 1

1

Well if Your $_POST[$val] does not exist, it'll throw that error.

If you replace if ( $_POST[ $val ] !== "" ) { with if ( empty($_POST[ $val ]) ) {, which checks if a variable is set and not empty, then you shouldn't be getting that error anymore.

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

1 Comment

no change specifying empty() instead. But good for you to point that out as I have been immersing myself in JS tuts lately and I find I am mixing conventions up lots. Cheers.

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.