Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I simplify this redundant code?

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).

like image 759
Alix Axel Avatar asked Dec 17 '22 00:12

Alix Axel


2 Answers

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...

like image 61
ircmaxell Avatar answered Dec 19 '22 13:12

ircmaxell


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];
like image 23
nico Avatar answered Dec 19 '22 13:12

nico