Page 1 of 1
help code explanation
Posted: Fri May 15, 2009 7:15 am
by szita1
Could anyone explain how the following code snippet works:
Code: Select all
$required = array("name" => "Your Name",
"email" => "Email Address");
foreach($required as $field => $label)
{
if (!$_POST[$field])
{
$warnings[$field] = "*";
}
}
when this code runs, it steps into "if" but i dont know why.
the "!" sign should prevent it to step in, shouldnt it.
thanks
Re: help code explanation
Posted: Fri May 15, 2009 7:22 am
by crazycoders
This is a really bad way of testing if a field was provided... The part where you see if(!$_POST[...]){ creates what we call a positive assertion if i do not name it wrongly...
Negative assertions
'', 0, NULL, false
Positive assertions
- anything that has a value
- true
- !NULL
So in this case, checking for each field in the post if it has a value creates a positive/negative assertion. By reversing the assertion using !, you create a weak testing mechanism to see if a value was submitted. If not, it sets a warning that a field was not provided.
Is it clear?
Re: help code explanation
Posted: Fri May 15, 2009 8:12 am
by szita1
I understood your explanation but I cant figure out how it works on this code.
Logically, when the "if (!$_POST[$blabla])" is evaluadted:
1. $blabla exists because $blabla has a value so $blabla is true;
2. the ! is there so the !$_POST[$blabla] is false;
3. so if (!$_POST[$blabla]) results false.
Where have I done wrong?
Re: help code explanation
Posted: Fri May 15, 2009 11:05 am
by ldougherty
If it is getting into the IF statement then obviously $_POST[$blabla] does not return a value. Try outputting the variable before the IF statement to see what it says.
echo $_POST[$blabla];
This should return nothing.
Re: help code explanation
Posted: Fri May 15, 2009 11:51 am
by crazycoders
Wait just there, your code should check errors or missing fields. If you do provide values to that script it will not return warnings, if don't send values it will send back warnings...
Re: help code explanation
Posted: Fri May 15, 2009 12:10 pm
by szita1
Yes, i see now. "echo $_POST[$blabla];" returns Null.
But... what Ive found interesting is that if it runs within a debugger(phpDesigner)
and i goes through step by step, the (!$_POST[$field]) shows the "name" value.
And this is a bit misleading.
Thanks for helping.