0

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.

3 Answers 3

6

Just use empty

if(!empty($args)){
  echo 'Array is set, not empty and not null';
}
Sign up to request clarification or add additional context in comments.

4 Comments

This couldn't be used if the variable happened to be a string right?
@shakabra: Why not?, you could.
empty() will check for empty strings, too. @shakabra you should take a good look at the manual page that was linked. It spells out exactly what the function does.
Ok I don't know why I haven't used this more often. Thanks for the answer. But will empty() work with database resources if I'm using MySQL. That's been a real headache for me.
1

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.

4 Comments

That's not PHP and it doesn't get anywhere close to covering all the use cases in my example.
@shakabra yes it is php, i should've included the link to manual page: php.net/manual/en/function.empty.php
@shakabra your example is also a bit different, it not only checks if $args has more than one element but also checks if $args[0] (the first element of $args) is an array as well
Sorry it was just a line of code that got me thinking about previous problems.
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.