How to filter_var_array sanitize all items and validate email programatically with PHP

Posted 3 years ago

I ran into a small problem where I wanted to sanitise all items within an array but I also wanted to verify that the submitted email was an actual email, I wanted to programatically loop through the array and ensure all data was cleaned up, but I wanted to check email was a valid email on its own.

Without going through and manually assigning arguments for each item, the only way I could get this to work was using PHP’s “filter_var_array” here http://php.net/manual/en/function.filter-var-array.php

    
    // Declare our array full of data
    $data = array(
      'one' => 'item one',
      'two' => 'item two',
      'email' => 'chris@me.com'
    )

    // declare our arguments array
    $args = array(); 

    // Loop through each item of our array
    // throw each items "key" into an array
    // and assign a validation argument
    foreach ($data as $k => $v) { 
      $args[$k] = FILTER_SANITIZE_STRING;
    }
    
    // Individually set the arguement for email. 
    $args['email'] = FILTER_VALIDATE_EMAIL;
    
    // if we printed our array we'd have this now
    //    'one' = FILTER_SANITIZE_STRING,
    //    'two' = FILTER_SANITIZE_STRING,
    //    'email' = FILTER_VALIDATE_EMAIL,
    
    // Perform our validation loop through our data array 
    // and check each item based on the arguments we've provided.
    $validate = filter_var_array($data, $args);