Search code examples
phpvariablesundefineddefined

How can I use my variable only if it is defined?


I like to use form[fieldsdata] only if it is defined:

  $fieldsJson = $data["form[fieldsdata]"] ? $data["form[fieldsdata]"] : "";

But still the error message is:

Notice: Undefined index: form[fieldsdata]


Solution

  • You can either use isset() to check if it's defined, or (if you're using PHP 7) use the null coalescing operator (??)

    Using isset

    $fieldsJson = isset($data["form[fieldsdata]"]) ? $data["form[fieldsdata]"] : "";
    

    Using null-coalescing operator (PHP 7 only)

    $fieldsJson = $data["form[fieldsdata]"] ?? "";
    

    Be aware that using null coalescing will also apply the empty string value if the index exists, but has a null value.