How could I compensate for the PHP code with many isset checks and repetitive, but variable-generating arguments?

Hey. I'm struggling to shorten a segment of code that looks pretty lengthy, and I'm not convinced of its materiality. This is a function for generating many session arrays used to fill out forms, and I have a check for the existence of certain values ​​in the array of arguments, and the cases for each of them generate the requested arrays. Here:

function prepOptional($formData) {

    $baseInfo=getBaseInfo();

    $_SESSION['fooData'] = (isset($formData['cbFoo']) ? prepBaseForm($baseInfo, 'foo',
            'Option foo') : '');

    $_SESSION['opt1Data'] = (isset($formData['cbOpt1']) ? prepBaseForm($baseInfo, 'opt1',
            'Option 1') : '');

    $_SESSION['barData'] = (isset($formData['cbBar']) ? prepBaseForm(prepOtherArray($formData), 'bar',
            'Option bar', 'Optional argument') : '');

}

The function takes an array of formdata as an argument, and depending on the values ​​contained, it generates the corresponding arrays in the session; this happens only after checking for the presence of a matching flag, therefore, etiquette and ternary operator.

prepBaseForm , , , ; , , .

, '', ( : , , , ?).

, ; , , , , , , , prepBaseForm . , ? .

+5
1

- , . , .:

function prepOptional($formData) {
    $baseInfo=getBaseInfo();

    $options = array(
        'foo' => 'Option foo', 
        'opt1' => 'Option Opt1',
        'bar' => 'Option Bar',
    );
    foreach ($options as $name => $text) {
        //Add defaults for formData and Session arrays)
        $formData += array('cb' . ucfirst($name) => '');
        $_SESSION += array($name . 'Data' => '');

        if ($formData['cb' . ucfirst($name)]) {
            $_SESSION[$name . 'Data'] = prepBaseForm(
                $baseInfo, 
                $name, 
                $text
            );
        }
    }
}
+4

All Articles