Search code examples
phpissetnull-coalescing-operator

How do I prevent `undefined index` by using values already set in a database by default?


I am working on an admin panel for my website that will change website settings. Everything works the way it's supposed to, except for the number of PHP warnings I get when a submit some values. I get the error undefined index. I know you can use isset(), but in my case, that would be very messy. How would I use a value in a database as a default value if my value is not set?

My code:

<?php
    
 if(!empty($_POST)) {
    $_POST['cms_and_posting'] = (bool) $_POST['cms_and_posting'];
    $_POST['google_verify'] = (bool) $_POST['google_verify'];
 }

?>

I have heard of something called the "null-coalescing-operator" in PHP, but I am a bit confused on how I would use that in my code.


Solution

  • You can use null coalescing operator.

     <?php
        
      if(!empty($_POST)) {
        $_POST['cms_and_posting'] = $_POST['cms_and_posting'] ?? $youdbvalue1;
        $_POST['google_verify'] =   $_POST['google_verify'] ?? $youdbvalue2;
      }
    
    ?>