Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP isset() redundant in this context?

Tags:

php

I am going through the "Head First PHP & MySQL" book right now, and on many parts of the book there are code snippets used to process HTML forms. They start like this:

if (isset($_POST['submit'])){
...
}

The if clause is used to detect if the form has been submitted already or not. Being used to programming in C mostly, I find that construct redundant and annoying (and I also don't think it helps code readability for experienced programmers). I would rather write it as:

if ($_POST['submit']){
    ...
}

Question: Is there some other reason to use isset() in this context that I might be missing? Would my version of the snippet be considered non-idiomatic PHP? What about in other contexts, can you give me an example of when isset() might be useful?

like image 767
Daniel Scocco Avatar asked Jan 17 '26 04:01

Daniel Scocco


1 Answers

There are situations where a variable is NULL, 0, or FALSE. They'd fail the if() {} comparison, but they are set.

Using isset() also avoids a notice about an undefined variable if your error_reporting settings include E_NOTICEs.

like image 97
ceejayoz Avatar answered Jan 19 '26 17:01

ceejayoz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!