Shortening PHP instead of repeating serveral code?

Discussion in 'PHP' started by crazyryan, Feb 27, 2007.

  1. #1
                        if (empty($_POST['title'])) {
                        echo "empty";
                        }
    
    PHP:
    With my above code, I want to check if $_POST['title'], $_POST['link_description'] and a few others are empty or not, instead of repeating the above code can I use like a comma or something somewhere so I can just do $_post['title'], $_post['link_description']

    ..etc

    Thanks
     
    crazyryan, Feb 27, 2007 IP
  2. wmtips

    wmtips Well-Known Member

    Messages:
    601
    Likes Received:
    70
    Best Answers:
    1
    Trophy Points:
    150
    #2
    You can use for example such a short construction:

    
    if (!@$_POST['title'] || !@$_POST['link_description'] || !@$_POST['field3'])
     echo "Wrong input";
    
    PHP:
     
    wmtips, Feb 27, 2007 IP
  3. rodney88

    rodney88 Guest

    Messages:
    480
    Likes Received:
    37
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Sure, just use a loop.
    $requiredFields = array('title','link_description','and_so_on');
    foreach ( $requiredFields as $field ) {
        if ( empty($_POST[$field]) ) {
            echo $field. ' is empty';
        }
    }
    PHP:
     
    rodney88, Feb 27, 2007 IP
  4. SedNaX

    SedNaX Active Member

    Messages:
    1,326
    Likes Received:
    59
    Best Answers:
    0
    Trophy Points:
    90
    #4
    That's easier for a few fields, but for a lot of fields use the loop.. little explanation for in the future ;)


    
    if (somthing == something_else || blablsfsdf == adas && as==asd) {
    }
    
    PHP:
    || means OR
    && means AND
     
    SedNaX, Mar 1, 2007 IP
  5. Barti1987

    Barti1987 Well-Known Member

    Messages:
    2,703
    Likes Received:
    115
    Best Answers:
    0
    Trophy Points:
    185
    #5
    
    foreach ($_POST as $key => $value)
    if($value == NULL){ $error .= 'Please enter a value for the '.$key.' field';}
    }
    if($error == NULL){
    //do your post stuff here
    }
    
    PHP:
    Peace,
     
    Barti1987, Mar 1, 2007 IP