How to treat null values ββas true using php?
Here's my sample code:
$issue_id = $_POST['issue_id'];
if(!empty($issue_id)){
echo 'true';
}
else{
echo 'false';
}
If I 0 to $_POST['issue_id']
submit over the submit form then it returns false. What I want: the condition will be true if the following conditions are true: 1. true when I pass any value that has 0. 2. false when I don't pass any value. ie: $_POST['issue_id']
undefined.
I also tried this:
if(!isset($issue_id)){
echo 'true';
}
else{
echo 'false';
}
if(!empty($issue_id) || $issue==0){
echo 'true';
}
else{
echo 'false';
}
The latter is fine, that is, if I pass in any value that has ZERO, then it will echo true. But it will also be true if I do not pass any value. Any ideas?
source to share
The latter is fine, that is, if I pass in any value that has ZERO then it will echo true. But this is also true if I donβt convey any value. Any idea?
if (isset($_POST["issue_id"]) && $_POST["issue_id"] !== "") {
}
Please note that I used !==
not !=
. that's why:
0 == "" // true
0 === "" // false
More details at http://php.net/manual/en/language.operators.comparison.php
also if you expect a number you can use
if (isset($_POST["issue_id"]) && is_numeric($_POST["issue_id"])) {
}
because it is_numeric("")
returns false
http://php.net/manual/en/function.is-numeric.php
Alternatively, if you expect parameter number to be good filter_var
if (isset($_POST["issue_id"]) {
$issue_id = filter_var($_POST["issue_id"], FILTER_VALIDATE_INT);
if ($issue_id !== false) {
}
}
since it filter_var("", FILTER_VALIDATE_INT)
will return false and filter_var("0", FILTER_VALIDATE_INT)
return(int) 0
source to share
When you receive data from a form, remember:
- All text boxes, whether
input
or nottextarea
, will display as strings . This includes blank text boxes and text boxes containing numbers. - All selected buttons will have a value, but buttons that are not selected will not be present at all. This includes radio buttons, checkboxes, and actual buttons.
This means there $_POST['issue_id']
will be a string '0'
that is actually true.
If you need to get an integer, use something like: $issue_id=intval($_POST['issue_id'])
;
source to share
@Abdus Sattar Bhuiyan you can also fill in all two conditions as below:
<?php
$_POST["issue_id"] = "0";
$issue_id = isset($_POST['issue_id']) ? (!empty($_POST['issue_id']) || $_POST['issue_id'] === 0 || $_POST['issue_id'] === "0") ? true : false : false;
if($issue_id){
echo 'true';
}
else{
echo 'false';
}
source to share