Can someone please help me simpling this redundant piece of code?
if (isset($to) === true)
{
if (is_string($to) === true)
{
$to = explode(',', $to);
}
$to = array_filter(filter_var_array(preg_replace('~[<>]|%0[ab]|[[:cntrl:]]~i', '', $to), FILTER_VALIDATE_EMAIL));
}
if (isset($cc) === true)
{
if (is_string($cc) === true)
{
$cc = explode(',', $cc);
}
$cc = array_filter(filter_var_array(preg_replace('~[<>]|%0[ab]|[[:cntrl:]]~i', '', $cc), FILTER_VALIDATE_EMAIL));
}
if (isset($bcc) === true)
{
if (is_string($bcc) === true)
{
$bcc = explode(',', $bcc);
}
$bcc = array_filter(filter_var_array(preg_replace('~[<>]|%0[ab]|[[:cntrl:]]~i', '', $bcc), FILTER_VALIDATE_EMAIL));
}
if (isset($from) === true)
{
if (is_string($from) === true)
{
$from = explode(',', $from);
}
$from = array_filter(filter_var_array(preg_replace('~[<>]|%0[ab]|[[:cntrl:]]~i', '', $from), FILTER_VALIDATE_EMAIL));
}
I tried using variable variables but without success (it's been a long time since I've used them).
Variable variables:
$vars = array('to', 'cc', 'bcc', 'from');
foreach ($vars as $varname) {
if (isset($$varname)) {
if (is_string($$varname)) {
$$varname = explode(',', $$varname);
}
$$varname = array_filter(filter_var_array(preg_replace('~[<>]|%0[ab]|[[:cntrl:]]~i', '', $$varname), FILTER_VALIDATE_EMAIL));
}
}
Regular (Without using variable variables):
$vars = compact('to', 'cc', 'bcc', 'from');
foreach ($vars as $name => &$var) {
if (is_string($var)) {
$var = explode(',', $var);
}
$var = array_filter(filter_var_array(preg_replace('~[<>]|%0[ab]|[[:cntrl:]]~i', '', $var), FILTER_VALIDATE_EMAIL));
}
extract ($vars);
Note, you don't need isset, because compact will only import variables that are set. All others are ignored...
BTW: You don't need the === true. isset() or is_string() will always return a boolean. So the === true is redundant...
You could do (untested)
$vars = array($from, $to, $cc, $bcc);
foreach ($vars as $var)
{
$var = explode(',', $var);
....
...
}
$from = $vars[0];
$to = $vars[1];
$cc = $vars[2];
$bcc = $vars[3];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With