3

I am always using the following code to check if an index exists and is not null:

if(!(isset($_POST['service']) and $_POST['service']))
   die('The service parameter is not available.');

Here I am checking two conditions. Is it possible to do it using a single buit-in function? eg:-

if(!isSetAndNotNull($_POST['service']))
   die('The service parameter is not available.');
pdu
  • 10,295
  • 4
  • 58
  • 95
Mohammed H
  • 6,880
  • 16
  • 81
  • 127
  • `$_POST` values cannot be `null`, and `isset` is already checking for `null`. You're checking if the string is `false`. – deceze Dec 14 '12 at 10:17
  • 1
    If you'd have just checked the "see also" section of the php isset manual page (http://php.net/isset) you'd have seen a reference to the ```empty()``` function... – dtech Dec 14 '12 at 10:18

2 Answers2

6

You should use empty() for that.

http://php.net/manual/en/function.empty.php

returns false for empty(false) or empty(null)

Najzero
  • 3,164
  • 18
  • 18
1

Rather than empty I would use !:

if(!$_POST['service'])
   die('The service parameter is not available.');

In case of using it with functions it avoid troubles.

Explanation here: https://stackoverflow.com/a/4328049/1081396

Community
  • 1
  • 1
Alvaro
  • 40,778
  • 30
  • 164
  • 336
  • You can read the problem you can find in the question of the link I posted. "Can't use method return value in write context" – Alvaro Dec 14 '12 at 10:23
  • 3
    The above code gives "PHP Notice: Undefined index: service in ..." – Mohammed H Dec 14 '12 at 10:24
  • 1
    @Steve That only exists if you use `empty` on a *function*, which it was not designed for and is not needed for. In this case he uses it for a variable, which is correct. The answer you link to explains why `empty` + function is wrong, not that you should always avoid `empty`. – deceze Dec 14 '12 at 10:25
  • Yeah, that's true @deceze. That's why i said *in some cases*. But you are right. – Alvaro Dec 14 '12 at 10:27
  • I can see your issue with empty(), but in his post-variable case it is just working fine. And youd better edit your if condition to `if(!$_POST['service'])` – Najzero Dec 14 '12 at 10:27
  • Anyway, +1 for giving light to the issue with empty(). – Mohammed H Dec 14 '12 at 10:32