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?

commnux
  • 485
  • 2
  • 9
  • 3
    Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) – Masivuye Cokile Mar 20 '17 at 09: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? – Afshan Shujat Mar 20 '17 at 09:15
  • did you validate your inputs to see if they are set and not empty? – Masivuye Cokile Mar 20 '17 at 09: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. – commnux Mar 20 '17 at 09:29

1 Answers1

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.

Asperitas
  • 339
  • 6
  • 13
  • 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. – commnux Mar 20 '17 at 09:22