Alok
Alok

Reputation: 2689

Check for non-empty variables

I have to check,say 20 variables. & I'm really confused between these two approaches to check whether all of them are non-empty.

First one is your basic approach:

if($var1!= null && $var2!= null && $var3!= null && $var4!= null...) {
    // Do this
}

Second approach is by using array which I got from here:

$vars = array('var1','var2','var3','var4');

$errors = array();         
foreach ($vars as $var => $label)
{
    if (isset($$var) && strlen($$var) == 0)
        $errors[$var] = $label . 'is empty';
}

if(is_array($errors) && count($errors) > 0)
{
    echo 'Please fix the following errors: ';
    echo '<ul><li>' . implode('</li><li>', $errors) . '</li></ul>';
}
else
{   
        //Do this
}

Now, like I said earlier, the variables in my situation are around 20. Which approach(If there are more, I would love to hear about them) do you suggest would be better(And more PHP-like if I may add), if the number of variables are as small as 20? Also, please be kind enough to explain as I'm still an newbee.

Thanks

Upvotes: 0

Views: 81

Answers (3)

Hanky Panky
Hanky Panky

Reputation: 46900

Let's say you have 10 such vars with that same naming convention as in your question. You could do

<?php

for ($i = 1; $i <= 10; $i++) {
    $var = "var$i";
    if (!empty($$var)) {
        // this one at $i is set
    } else {
        // not set
    }
}

You can just change the loop's upper limit to count for the number of variables that you have. Without having to first generate an array of names by hand. But still if you have so many variables with same name and just the index is different then you're better off using an array in the first place.

Upvotes: 2

hek2mgl
hek2mgl

Reputation: 157947

The second attempt is ok, but this line:

if (isset($$var) && strlen($$var) == 0)

might be:

if (empty($$var))

.. depending on your needs. If using empty(), variables which have been set to:

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • $var; (a variable declared, but without a value)

will be treated as empty

Upvotes: 3

hansn
hansn

Reputation: 2024

You could use the empty function.

function noneEmpty($array) {
    foreach ($array as $variable)
        if (empty($variable))
            return false;
    return true;

Upvotes: 1

Related Questions