PHP, what is the easiest way to determine that a field submitted is not empty?
Reply content:
PHP, what is the easiest way to determine that a field submitted is not empty?
Submit a field Ah! Must be _POST
, _GET
even _REQUEST
, rather than simply discuss $var
!
To prevent three cases:
- There is no such field at all in the commit (if not processed, the subscript does not exist will throw a run-time error directly)
- The submitted field is empty
- The field after the submission
trim()
is empty
If it is native PHP, I recommend the following steps:
- The principle is preprocessing first
$_POST
.
$_POST
strip all the elements of the end and end of the space.
$_POST
throw away all the empty elements in it.
- In this way, the surviving elements in the array are not empty. Determine if the element exists.
Pay attention to the second and third steps, do not fool with foreach
their own loops, it is best to use the array function of a few traversal functions. Code:
$_POST = array_map('trim', $_POST);$_POST = array_filter($_POST);$result = array_key_exists('fieldname', $_POST);if ($result) { // do whatever you wish}
This is simple enough, but the problem is that portability is poor (because you need to rely on pre-treatment before). If you want to be portable and good, look simple, judge and comprehensive, write your own function.
if(trim($var) != ''){ // code here}
if(!empty($var)){ //code here}
Personal prefer to use isset () to judge, all done.
if( isset( $_GET['password'] ) ) { // do something}