I have a field in a form for entering the number of masters titles won by a Tennis player. Some players have 0 titles. Even though my validation checks for an empty field I cannot enter 0. What changes do I need to make to allow 0 to be entered?
if (empty($_POST["masters"])) {
$has_errors = true;
$mastersErr = "Enter 0-10";
} else {
$masters = validate_input($_POST["masters"]);
}
use if ($_POST["masters"] === '') { to check for empty string
this is because
empty($variable) returns true if $variable equals false, null, '' (empty string) or 0
you can't use $_POST['masters'] == '' because in PHP statement 0 == '' is true
you have to use === operator
please also mind $_POST['xxx'] === 0 will never work because values in $_POST are strings
Anyway if you want user to put number between 0-10 I would suggest to do this check
if(is_numeric($var) && ($var >= 0) && ($var <= 10) && (intval($var) == $var))
{
// OK
}else
{
// not OK
}
This is because space character will pass $_POST["masters"] === '' check.
In validation you should always create if statements keeping in mind to check "is this value OK", not "is this value bad". For example if you want to validate email you dont' check "is value empty" "is value a number" "is value a float", you check "is value a email"|
is_numeric() is good, because
is_numeric('') is false
is_numeric(' ') is false
is_numeric(0) is true
but beware! because
is_numeric('0.1') is also true...
...so you need another check:
(intval($var) == $var) - this is how you make sure user entered integer (not float) number
PHP Manual:
http://www.php.net/manual/en/language.operators.comparison.php
http://www.php.net/is_numeric
http://www.php.net/intval
Related
My code looks like this:
$muted = 'true'; //Note this is only for testing
if ($muted == 'false' || $muted == '' || $do_not_text == '' || $do_not_text =='false'){
//do this first thing
}
else{
//do something else
}
I can't get my else to run. What syntax am I messing up?
Related to this, I'm storing a value in my database (that will be what's called to set $muted in my real code) that's either 'true', 'false', or ''. What data type should I be storing these as? Currently, I'm using VARCHAR, but I suspect this is all part of the problem.
$do_not_text == '' evaluates to true. Why? Because $do_not_text is not defined which is a falsy value. You are comparing it to an empty string which also equates to a falsy value. So that comparison is true causing the first if statement to be evaluated as true.
I'm not sure why you're using strings for what should be boolean values.
$muted = true; // no need for quotes
You might also consider using the === operator when comparing boolean values.
if ($muted === false || // etc...
What data type should I be storing these as?
Boolean values in MySQL are typically stored as 1 or 0.
field_name TINYINT(1) UNSIGNED NOT NULL DEFAULT 0
Store them as TINYINT with length of 1 because its only 1 and 0, and 0 as the default value.
Then you can make $muted = boolval($db_muted_val); if you want, or use $db_muted_val as is, because 1 is true and 0 is false.
if ($db_muted_val) {
// do this first thing
} else {
// do something else
}
I want to validate a field which is required. I am using following condition to check whether the field is not empty:
isset($value) && !empty($value)
But if I write 0 in the fields, it will still say the field is required. The empty() function considers 0 as an empty value as told in PHP manual but what else should I do? I have tried writing many conditions but they didn't work as expected.
I saw user contributions and found:
empty($var) && !is_bool($var)
I tried adding it to my condition like this but didn't work:
isset($value) && !empty($value) && is_bool($value)
Try below code:
$value = 0;
if(isset($value) && $value !== "")
{
echo "Field not required";
}
else
{
echo "Field required";
}
Output:
Field not required
Demo:
http://3v4l.org/JWJbj
Explanation:
The integer 0 is truthy. It means that anything that checks it in a boolean'ish manner will treat it as false. In particular, !empty($value) will evaluate to false, so is_numeric would never even get a chance to fail.
Short version: empty is too wishy-washy in this case. Check for null and '' explicitly (with data-type hence used !==).
You can't check for empty. Basically you can only stick to the isset test.
If a field in the form was not filled this variable field will not be inside the $_POST superglobal and isset will return false. If the user typed 0 the variable name will exist inside $_POST isset will return true.
I would do it as following:
function emptyTextValue($value)
{
return trim((string) $value) !== '';
}
You know that all you get is a string, so you don't need full functionality of empty() function:
isset($_POST['yourFieldName']) && $_POST['yourFieldName'] !== ''
You can replace the empty function by :
$value !== ""
If it's not exactly empty, then it will validate the condition.
What I've done for my test is convert the empty check to a strlen check. Because PHP is so friendly, you can run a string comparison on the value. A value of null will return a 0 length string, while a value of 0 will return a length of 1. So what I've done is this:
if(isset($val) && strlen($val) > 0){
// Do stuff
}
Try
isset($value) && $value != ''
I have found a nice condition by myself.
$value === 0 || $value === "0" ? isset($value) : isset($value) && !empty($value)
This works perfectly for every case.
I would check to be sure that the form had been submitted and then trim the field 'msg' in case there were any white space chars, i.e. newlines, carriage returns, tabs, spaces and then test that result to make sure it's not the empty string as follows:
<?php
if ( isset($_POST['msg']) && trim($_POST['msg']) !== '') {
// other code
}
I'm trying to determine whether or not there is a value passed, but the value CAN be 0 ...
isset always returns true, and empty returns false because the value is 0
How can I get around this?
try
bool array_key_exists ( mixed $key , array $array )
like
if (array_key_exists("var1", $_POST)) {
// positive case, var1 was posted
if ($_POST["var1"] == 0){
// var1 was posted and 0
}else{
// var1 was posted and is not 0
}
}
more details are given at the docs.
The values of the $_POST array is all strings. Use the === operator:
if ($_POST['key'] === '0') {
// do things
}
Try this
if (isset($_POST['name']) && $_POST['name'] != 0)) {
/your Code/
}
What about simply checking whether the value is empty:
if (isset($_POST['key']) && $_POST['key'] !== '')) {
//'key' is set and not empty
}
All post values are strings, so consider:
isset($a[i]) && strlen($a[i])
Which will be true if and only if a value (except "an empty string") is supplied. Unlike with empty, which would return FALSE, this will also detect when "0" was passed as a value. Unlike the proposed solution, it will not be true when "" was supplied: thus it truly detects when a value was passed.
Also, array_key_exists and isset for $_POST keys will work the same, as there will no NULL values; arguably the critical check is that for a non-empty string. Once a value has been determined to exist (per the above/desired rules), it can be processed as appropriate - e.g. if ($a[i] > 0) or if ($a[i] == 0).
How do I write an if condition that will evaluate a zero as not empty? I'm writing a validation script and if the field is blank, I throw an error. In the case of a select with numerical values that start with 0 (zero), that should not considered to be empty. The manual states that a string 0 is considered to be empty and returns false. If I change empty to !isset, the zero works but the other textboxes that are truly empty pass validation. How do I write this to handle my case?
if (strlen($x)) {
// win \o/ (not empty)
}
Happy coding.
(All text box / form input content is inherently just text. Any meaning as a numerical value comes later and each representation can be validated. 0 is coerced back to "0" in strlen.)
Have you considered using is_null()?
if (is_null($value) || $value === "") {}
if (empty($value) && $value !== 0)
if(!is_numeric($var) && empty($var))
{
// empty
}
else
{
// not empty
}
In PHP, how would one check to see if a specified item (by name, I think - number would probably also work) in an array is empty?
Types of empty (from PHP Manual). The following are considered empty for any variable:
"" (an empty string)
0 (0 as an integer)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
So take the example below:
$arr = array(
'ele1' => 'test',
'ele2' => false
);
1) $arr['ele3'] is not set. So:
isset($arr['ele3']) === false && empty($arr['ele3']) === true
it is not set and empty. empty() checks for whether the variable is set and empty or not.
2) $arr['ele2'] is set, but empty. So:
isset($arr['ele2']) === true && empty($arr['ele2']) === true
1) $arr['ele1'] is set and not empty:
isset($arr['ele1']) === true && empty($arr['ele1']) === false
if you wish to check whether is it empty, simply use the empty() function.
if(empty($array['item']))
or
if(!isset($array['item']))
or
if(!array_key_exists('item', $array))
depending on what precisely you mean by "empty". See the docs for empty(), isset() and array_key_exists() as to what exactly they mean.
<?php
$myarray=array(1,5,6,5);
$anotherarray=array();
function checkEmpty($array){
return (count($array)>0)?1:0;
}
echo checkEmpty($myarray);
echo checkEmpty($anotherarray);
?>
(for checking if empty result 1 else 0);
Compactness is what I persue in my code.
i had such situation where i was getting tab it last index of array so if put things together then this might work for the most of cases
<?php
if( ctype_space($array['index']) && empty($array['index']) && !isset($array['index']) ){
echo 'array index is empty';
}else{
echo 'Not empty';
}