Skip to content
Advertisement

How can I get an array from an If statement?

I’m trying to detect conditions of a string length within input fields. I need to know which condition(s) is met from the if statement and then put that/those in an array to display. Here’s my code:

                if(strlen($post['first_name']) > 25
                    || strlen($post['last_name']) > 25
                    || strlen($post['email']) > 40
                    || strlen($post['phone']) > 15
                ){
                  $lengthTooLong = array();  
                  //do this
                }

Advertisement

Answer

You can use foreach.

// define which keys of $post you want to check
// array value defines max length of value from $post[$key]
$keyToMaxLength = array(
    'first_name' => 25,
    'last_name' => 25,
    'email' => 40,
    'phone' => 15,
);
$lengthTooLong = array();
foreach($keyToMaxLength as $key => $maxLength) {    
    if(strlen($post[$key]) > $maxLength) {
        $lengthTooLong[] = $key; // or $post[$key]
    }
}
echo var_export($lengthTooLong, true); 

Working example

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement