1

If I want to check if element(e.g. $_POST['name']) exists I do that:

A.) if(isset($_POST['name']))

If I want to see if element exists and is not empty, I do B.) or is it C.) enough?

B.) if(isset($_POST['name']) && !empty($_POST['name']))

C.) if(!empty($_POST['name']))

I've tried and C.) worked fine, but reputable school always used B.) approach and I asked my instructor there and she said I should use B.) approach, although I am not clear why and I decided to ask here to be sure and not to do an overkill if it is not necessary. [They didn't explain me why.] Can You give me some examples why I should use B.) over C.)?

Thanks and have a great and good day, Gregor Leskovšek from Slovenia

Per76
  • 184
  • 1
  • 1
  • 15
user1081168
  • 49
  • 1
  • 6
  • C only works fine on servers set to not throw an error when encountering an index that doesn't exist. Move that code to a different server, and it might break. – developerwjk May 05 '15 at 20:11
  • 1
    `isset` checks for variable presence, and `empty` for *truthiness* (empty strings and zeroed strings are considered falsy). So depends on what you want to accomplish. An isset/strlen combo is actually what most use cases call for. – mario May 05 '15 at 20:13
  • This question has already been answered: http://stackoverflow.com/questions/4559925/why-check-both-isset-and-empty – Per76 May 05 '15 at 20:16
  • This guide will learn you "everything" about isset and empty: http://kunststube.net/isset/ – Per76 May 05 '15 at 20:19
  • I always recursively `trim()` the POST array with a custom `trim_r($_POST)` function and then use `if(isset($_POST['name']) && $_POST['name'] !== '')` – MonkeyZeus May 05 '15 at 20:20
  • user please mark and up-vote the answer for others help. thanks – Alive to die - Anant Feb 03 '16 at 09:46
  • People are interested in getting answers but not interested in marking the answers. really frustrating. deleting my answers. – Alive to die - Anant Mar 25 '16 at 20:06
  • I am sorry I did not get this one. I do not have reputation to vote. And what will the answer be in PHP 7 ?? ternary shortest and safest? – user1081168 Mar 26 '16 at 03:34

0 Answers0