Reputation: 45
So I've got a form with a modal, that modal has 3 rows with 2 text fields each, if the user (me in this prod case) fills out only 2 rows, and leave the other row empty, that 3rd value should be NULL.
In my script I've got:
if (!is_null($_POST['packageDependencies']['bundle'][2])) {
$packageDependency3 = $_POST['packageDependencies']['bundle'][2] . "|" . $_POST['packageDependencies']['version'][2] . "|" . $_POST['packageDependencies']['repository'][2];
$depends = "<key>dependencies</key>
<array>
<string>$packageDependency1</string>
<string>$packageDependency2</string>
<string>$packageDependency3</string>
</array>
";
}
So I'm checking if (!is_null($3rdRow)) { //Do this }
, but the variable $_POST['packageDependencies']['bundle'][2]
is in fact NULL, as I use var_dump($_POST['packageDependencies']['bundle'][2]);
and I get NULL
printed to the page, but the if
statement is still processing as if it isn't NULL
.
$depends
gets fwrite()
to an XML file, and when I open it, I only see ||
and but that shouldn't be there as the variable is NULL as I entered no values into those input fields.
Upvotes: 1
Views: 39
Reputation: 45
Even though !empty()
did the trick, I've decided to use ==
to be less ambiguous. The answers found here are quite intuitive.
EDIT: As per @gview, adding (!empty(trim($var)))
is the best bet as if a user accidentally presses the space key after a tab, it will avoid any errors.
Upvotes: 0
Reputation: 15361
Given my advice, a more complete solution would be:
if (!empty(trim($_POST['packageDependencies']['bundle'][2]))) {
NULL is a specific state of a variable that involves the way PHP associates the name of a variable with a variable location. You can think of it like a flag, that indicates a variable name exists, but there is no storage location associated with it. There are a number of situations that empty with trim will catch that will bypass a check against null.
Upvotes: 1