3v4l.org

run code in 300+ PHP versions simultaneously
<?php function validate_length ($options = ['min_length' => 1, 'max_length' => null], $filters = null) { return static function ($value = null) use ($options, $filters) { $len = strlen($value); if (isset($options['min_length']) && $len < $options['min_length']) { return false; } if (isset($options['max_length']) && $len > $options['max_length']) { return false; } if (null !== $filters) { return filter_var($value, ...$filters); //php 5.6+ array spread operator } return $value; }; } $a = [ 'a' => 'value', 'b' => '', 'c' => 'a@example.com', 'd' => 'This& is a 🍕 Test', ]; $email_filter = [FILTER_VALIDATE_EMAIL, ['flags' => FILTER_FLAG_EMAIL_UNICODE]]; $string_filter = [FILTER_SANITIZE_STRING, ['flags' => FILTER_FLAG_ENCODE_AMP | FILTER_FLAG_STRIP_HIGH]]; $result = filter_var_array ($a, [ 'a' => ['filter' => FILTER_CALLBACK, 'options' => validate_length(['max_length' => 4])], 'b' => ['filter' => FILTER_CALLBACK, 'options' => validate_length(['min_length' => 1])], 'c' => ['filter' => FILTER_CALLBACK, 'options' => validate_length(['min_length' => 1, 'max_length' => 20], $email_filter)], 'd' => ['filter' => FILTER_CALLBACK, 'options' => validate_length(['min_length' => 1], $string_filter)], ]); var_dump($result);

preferences:
23.65 ms | 406 KiB | 5 Q