I have a form that sets up the page's input field values using PHP like:
// create and fill inputVarsArr with keys that have empty vals
$troubleInsertInputVarsArr = array_fill_keys(array('status', 'discoverDate', 'resolveDate', 'ticketIssued', 'eqptSystem', 'alarmCode', 'troubleDescription', 'troubleshootingSteps', 'resolveActivities', 'notes'), '');
if (isset ($_POST['insert'])) { // update DB site details
foreach ($troubleInsertInputVarsArr as $key => $val) {
if ($key !== 'discoverDate' && $key !== 'resolveDate') { //deal with dates separately below
$val = $_SESSION[$key] = sanitizeText($_POST[$key]);
echo '<br>(' . __LINE__ . ') ' . $key . ': ' . $val . ' ';
} // close IF ; line 47 echo
} // close FOREACH
foreach ($troubleInsertInputVarsArr as $key => $val) {
echo '<br>(' . __LINE__ . ') ' . $key . ': ' . $val . ' ';
} // close FOREACH // line 52 echo
}
The input vars echo'd in the if
conditional nested in the foreach
loop (echo' on line 47) print out as I expect (values entered into the form page's input fields):
(47) status: Outstanding
(47) ticketIssued: no
(47) eqptSystem: Tower Lights
(47) alarmCode: Visual
(47) troubleDescription: - no description yet -
(47) troubleshootingSteps: - no steps yet taken -
(47) resolveActivities: - no activities yet decided -
(47) notes: - no notes -
But then the same key-val pairs in the same array echo'd in the foreach
loop that immediately follows (echo'd on line 52), without any further variable processing having occurred, prints out empty values for each key:
(52) status:
(52) discoverDate:
(52) resolveDate:
(52) ticketIssued:
(52) eqptSystem:
(52) alarmCode:
(52) troubleDescription:
(52) troubleshootingSteps:
(52) resolveActivities:
(52) notes:
Somehow the array's key values are being zero'd out right after they are assigned and I can't figured out how or why. Can anyone see an obvious reason why this might be occurring?
You never assign values to $troubleInsertInputVarsArr, only keys. You could try this:
foreach ( $troubleInsertInputVarsArr as $key => $val ) {
$troubleInsertInputVarsArr[$key] = sanitizeText( $_POST[ $key ]);
if ( $key !== 'discoverDate' && $key !== 'resolveDate' ) {
$val = $_SESSION[ $key ] = sanitizeText( $_POST[ $key ] );
echo '<br>(' . __LINE__ . ') ' . $key . ': ' . $val . ' ';
}
}
The $val = $_SESSION[ $key ] = sanitizeText( $_POST[ $key ] );
line does not change the $troubleInsertInputVarsArr
array as $val
is a copy of the array element value, not a reference.
Change the foreach so that $val is a reference.
foreach ( $troubleInsertInputVarsArr as $key => &$val ) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With