PHP Get Multi Select List Values

834 views Asked by At

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

There are 2 answers

2
Jon On BEST ANSWER

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

$mcField = isset($_POST[$mcFieldName]) ? $_POST[$mcFieldName] : null; 
0
zerkms On

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

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