Posted By

jamepaul on 09/02/10


php validator

Versions (?)

POST or GET data empty check

 / Published in: PHP

I don't want to write function empty() again and again.

  1. <?php
  2. function check_empty($args=array()) {
  3. foreach($args as $arg) {
  4. if (empty($arg)) {
  5. return false;
  6. }
  7. }
  8. }
  9. ?>

Report this snippet  


RSS Icon Subscribe to comments
Posted By: Sverri on December 21, 2010

This function is nonsensical.

The empty() function will return true if the POST or GET arrays are empty. There is no need to loop over the values like this.

Posted By: jamepaul on December 23, 2010

I don't directly loop POST or GET. I use like this.

$val1 = $POST['val1']; $val2 = $POST['val2']; $val4 = $_POST['val3'];

$arr = array($val1, $val2, $val3);

if(check_empty($arr) === false) { // codes here }

Any advice?

Posted By: Sverri on January 2, 2011

Okay, but I am not quite sure in what situation a function like that would be useful.

If you want to know if an array is empty simply use:

if (empty($array)) {
    echo "The array is empty";

If you want to know if an array is NOT empty. ("!" means "not" and basically flips boolean values on their heads, so that false becomes true and vice versa):

if ( ! empty($array)) {
    echo "The array is NOT empty";

if you want to know if an array CONTAINS one or more empty values.

if (in_array(null, $arr)) {
    echo 'Array contains one or more empty values';

In PHP if a value can be thought of as empty it is considered to be of the type null: 0 (zero), false (boolean), "" (empty string), array() (empty array), 0.0 (empty decimal number), and so on, are all considered to be null. Be careful, though, to not use === in cases like this, because === also checks for the variable type and then the aforementioned values will not equal null.

Also, you should take a look at PHP's array functions. It is rare that you need to define your own functions for use with arrays.

Anyways, so you can do something like this:

$arr = array($POST['val1'],$POST['val2'],$_POST['val3']);
if (in_array(null, $arr)) {
    echo 'Array contains one or more empty values';

You need to login to post a comment.