Skip to content

Instantly share code, notes, and snippets.

@PhilZ-cwm6
Last active April 9, 2022 15:55
Show Gist options
  • Save PhilZ-cwm6/4676368b77fc01d478f42b5c94f26a66 to your computer and use it in GitHub Desktop.
Save PhilZ-cwm6/4676368b77fc01d478f42b5c94f26a66 to your computer and use it in GitHub Desktop.
php empty form field
<!DOCTYPE html>
<html>
<body>
<?php
function empty_field_empty($str) {
return empty($str);
}
function empty_field_isstr($str) {
$has_text = !is_string($str) && strlen($str) > 0;
return !$has_text;
}
function empty_field_isbool($str) {
$has_text = !is_bool($str) && strlen($str) > 0;
return !$has_text;
}
$arr = array("NULL"=>NULL,
"bool+"=>true,
"bool-"=>false,
"empty"=>"",
"num 0"=>0,
"num 1"=>1,
"space"=>" ",
"str 0"=>'0',
"str 1"=>'1',
"str 1"=>'1',
"str true"=>'true',
"str false"=>'false');
echo "</br></br>Is empty field, using empty():</br>";
if (empty_field_empty($x)) {
echo "unset -> true</br>";
} else echo "unset -> false</br>";
foreach ($arr as $key => $val) {
if (empty_field_empty($val)) {
echo "$key -> true</br>";
} else echo "$key -> false</br>";
}
echo "</br></br>Is empty field, using is_string and strlen:</br>";
if (empty_field_isstr($x)) {
echo "unset -> true</br>";
} else echo "unset -> false</br>";
foreach ($arr as $key => $val) {
if (empty_field_isstr($val)) {
echo "$key -> true</br>";
} else echo "$key -> false</br>";
}
echo "</br></br>Is empty field, using is_bool and strlen:</br>";
if (empty_field_isbool($x)) {
echo "unset -> true</br>";
} else echo "unset -> false</br>";
foreach ($arr as $key => $val) {
if (empty_field_isbool($val)) {
echo "$key -> true</br>";
} else echo "$key -> false</br>";
}
?>
</body>
</html>
@PhilZ-cwm6
Copy link
Author

Output:
Is empty field, using empty():
unset -> true
NULL -> true
bool+ -> false
bool- -> true
empty -> true
num 0 -> true
num 1 -> false
space -> false
str 0 -> true
str 1 -> false
str true -> false
str false -> false

Is empty field, using is_string and strlen:
unset -> true
NULL -> true
bool+ -> false
bool- -> true
empty -> true
num 0 -> false
num 1 -> false
space -> true
str 0 -> true
str 1 -> true
str true -> true
str false -> true

Is empty field, using is_bool and strlen:
unset -> true
NULL -> true
bool+ -> true
bool- -> true
empty -> true
num 0 -> false
num 1 -> false
space -> false
str 0 -> false
str 1 -> false
str true -> false
str false -> false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment