noel
noel

Reputation: 2339

PHP test for empty and/or null and/or unset array

I want to keep this short. I don't know if I have the terminology correct, but I got this example from the Codeigniter handbook Vol.1.

if (count($args) > 1 || is_array($args[0]))

I've run into this problem numerous times. Depending on the datatype different tests are more appropriate. Some tests will just fail in unexpected ways.

How does one determine the most appropriate, and possibly, the most concise test?

Just to be clear I'm looking for the most effective way to test if an object/variable is ready to use, regardless of the datatype, if that's possible.

Also I don't want the solution to apply merely to lists like in the example. It should be widely applicable.

Upvotes: 0

Views: 12037

Answers (3)

Jonathan Roy
Jonathan Roy

Reputation: 903

I've been using the following function for a while.

You can add your own test for all possible variable types.

function is_valid_var($var)
{
  if ( isset( $var ) ) {

    // string
    if ( is_string( $var ) && strlen( $var ) == 0 ) return false;

    // array
    elseif ( is_array( $var ) && count( $var ) == 0 ) return false;

    // unknown
    else return true;
  }

  return false;
}

Upvotes: 0

Shakti Singh
Shakti Singh

Reputation: 86386

Just use empty

if(!empty($args)){
  echo 'Array is set, not empty and not null';
}

Upvotes: 6

interskh
interskh

Reputation: 2591

use empty() bool empty ( mixed $var )

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

Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.

Upvotes: 1

Related Questions