0

I'm trying to write a simple function to construct field names for a form. It works fine if at least one value is selected in a multi-select list but if nothing is selected I get an Undefined index error. Here is what I have:

function mcFieldName($mcFieldName){
$mcField = $_POST[$mcFieldName];
if( !is_array($mcField) ){
    if( !empty($mcField) ){
        return $mcField;
    }else{
        return 'n/a';
    }
}
if( is_array($mcField) ){
    $mcFieldArray = implode(',', $mcField);
    return $mcFieldArray;
}

}

$MultiSelect = mcFieldName('mcMultiSelect');
// test
echo $MultiSelect . '<br/>';

Thank you!

2 Answers 2

1

You just need to protect yourself from reading a key that does not exist in $_POST:

$mcField = isset($_POST[$mcFieldName]) ? $_POST[$mcFieldName] : null; 
Sign up to request clarification or add additional context in comments.

2 Comments

I tried the isset and !empty but neither of them worked. I don't understand the null part.
@user1002039: What this does is set $mcField to the field's value if one was posted, or to null if one was not. Your existing code would then react to the null value by returning "n/a". I 'm not sure what you mean "you tried and neither worked".
1

Before you try to access an array item make sure it exists with using isset():

if (isset($_POST[$mcFieldName])) {
    $mcField = $_POST[$mcFieldName];
    ...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.