How to use IF Statement in WordPress?

I can’t see how to correctly use the PHP if statement in my filter function below. This code works perfectly if all (3) of my $_POST inputs have values however it has a fatal error if any are empty. So I’d like to tell it to not run any code of any of these inputs are empty.

add_action( 'gform_after_update_entry_7', 'add_length_on_update', 10, 2 );
function add_length_on_update( $form, $entry_id ) {

// get input from form
$date = $_POST["input_3"];
$start = $_POST["input_27"];
$end = $_POST["input_28"];

// convert date and time arrays into datetime formats
$startdate = DateTime::createFromFormat('m/d/Y@h:i a', $date . "@". $start[0].":".$start[1]." ".$start[2]);
$enddate =   DateTime::createFromFormat('m/d/Y@h:i a', $date . "@". $end[0].":".$end[1]." ".$end[2]);

//convert datetimes into seconds to compare
$starttime = strtotime($startdate->format('Y-m-d H:i:s'));
$endtime = strtotime($enddate->format('Y-m-d H:i:s'));

// check to see if the times span overnight
if($starttime > $endtime) {
    $endtime = strtotime($enddate->format('Y-m-d H:i:s') . " +1 day");
}

// perform calculation
$diff = floor(($endtime - $starttime)/30);

GFAPI::update_entry_field( $entry_id, 32, $diff );

}

1 Answer
1

Here you go..

add_action( 'gform_after_update_entry_7', 'add_length_on_update', 10, 2 );
function add_length_on_update( $form, $entry_id ) {
    if( !empty($_POST["input_3"]) && !empty($_POST["input_27"]) && !empty($_POST["input_28"]) ){
        // get input from form
        $date = $_POST["input_3"];
        $start = $_POST["input_27"];
        $end = $_POST["input_28"];

        // convert date and time arrays into datetime formats
        $startdate = DateTime::createFromFormat('m/d/Y@h:i a', $date . "@". $start[0].":".$start[1]." ".$start[2]);
        $enddate =   DateTime::createFromFormat('m/d/Y@h:i a', $date . "@". $end[0].":".$end[1]." ".$end[2]);

        //convert datetimes into seconds to compare
        $starttime = strtotime($startdate->format('Y-m-d H:i:s'));
        $endtime = strtotime($enddate->format('Y-m-d H:i:s'));

        // check to see if the times span overnight
        if($starttime > $endtime) {
            $endtime = strtotime($enddate->format('Y-m-d H:i:s') . " +1 day");
        }

        // perform calculation
        $diff = floor(($endtime - $starttime)/30);

        GFAPI::update_entry_field( $entry_id, 32, $diff );
    }   
}

Leave a Comment