Search code examples
phpisset

How to combine isset with is_array


I am using is_array function but need to use isset as well, as if nothing is selected I am get a undefined index error.

I am still learning PHP so not sure how to combine what I have written with isset, my code is below

$special = $_POST['special'];
if (is_array($_POST['special'])) {
    $special = implode(",", $_POST['special']);
} else {
    $special = $_POST['special'];
}

Many Thanks


Solution

  • You are attempting to assign the value of $_POST['special'] to $special whether it is set or not. That is why you are getting an error. The following might work:

    $special = ""; 
    if (isset($_POST['special'])) {
        if(is_array($_POST['special'])) {
            $special = implode(",", $_POST['special']);
        } else {
            $special = $_POST['special'];
        }
    } 
    

    If $_POST['special'] is an array it will use implode to convert it to a string and assign it to $special.

    If it is not an array, but is still set, then assign the value to $special