PHP, what is the easiest way to determine that a field submitted is not empty?

Source: Internet
Author: User
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:

    1. 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)
    2. The submitted field is empty
    3. The field after the submission trim() is empty

If it is native PHP, I recommend the following steps:

    1. The principle is preprocessing first $_POST .
    2. $_POSTstrip all the elements of the end and end of the space.
    3. $_POSTthrow away all the empty elements in it.
    4. 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}
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.