How to optimize multiple (!$vars) ...?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
rxsid
Forum Commoner
Posts: 82
Joined: Thu Aug 29, 2002 12:04 am

How to optimize multiple (!$vars) ...?

Post by rxsid »

Hi all,
How could I optimize this server side check for missing form data?

Code: Select all

if(!$varA || !$varB || !$varC || !$varD || !$varF || !$varG) {
   //some error for missing form data
}
Can the var's to check be put in some kind of array?

thanks...
User avatar
QWERTY
Forum Newbie
Posts: 20
Joined: Sat Jun 29, 2002 10:57 am
Location: Slovenia

...

Post by QWERTY »

Create an array with names of variables, than do foreach() and create a string for matching in IF sentense ( $var1 || $var2, etc ... ). Then use eval() to create IF() ...

Code:

Code: Select all

<?php
$arrayVariables = array( "varA", "varB", "varC", "varD" );

    $intX = 0;
    $intNumOfValues = count( $arrayVariables );
foreach( $arrayVariables AS $strVariable )&#123;
    $intX++;
        if( $intX == $intNumOfValues )&#123;
            $strToEval .= "\$" . $strVariable;
        &#125;else&#123;
            $strToEval .= "\$" . $strVariable  . " || ";
        &#125;
&#125;

eval( "if( " . $strToEval . " )&#123; echo "Yeah";&#125;else&#123; echo "Nooo";&#125;" );

?>
Something like that ...
Post Reply