How to return the name of a variable evaluated in a condition

coldfusion evaluate dynamic variable
python returns none instead of value
javascript eval alternative
python function return variable
eval js
python check if function returns true
javascript eval function string
how to return a function in python

I want to find out the name of the first variable that has false value while checked in a condition. For example:

if (!$value1 || !$value2 || !$value3){

    // return the name of the first false variable - but how?
}

PHP evaluates the conditions in brackets and if one of the variables is false then we execute the code. The trick is how to make PHP to tell me which variable is false without examining them manually one by one again. Any ideas?

So far I have one idea, but it's very inefficient.

function checkFalseVars($vars){

    foreach($vars as $var){

        $v = $GLOBALS[$var];
        if (!$v){
            return $var;
       }    
    }
    return false;
}  

$value1 = true;
$value2 = false;
$value3 = false;

$vars = array('value1','value2','value3');


if (!$value1 || !$value2 ||!$value3){

    return  checkFalseVars($vars);
    // returns 'value2'
}

It sounds like you're averse to your current implementation due to the repeated iteration over the variables (in the if statement, and in your checkFalseVars function). Your implementation is correct in that if you want to find out which variable is false, you will need to iterate over them, and there's no way around that.

So at this point, you need to take a step back and assess your code, since you don't want to be repeating anything. Since you have to loop over the variables anyway, you may as well have your if statement look at the result of that loop, rather than have the if statement assessing each variable itself. Since your checkFalseVars function returns a false value if none of the variables are false, then you can simply have your if statement check the output of that function.

Here is a minor refactoring of your code - I've kept your checkFalseVars function as-is. This has the added benefit of keeping the variable checking in a single function, so that if you add more variables to check, you only have to add them to the array that you're passing to the function...You don't need to worry about keeping the variable checking in the if statement up to date as well.

function checkFalseVars($vars){

    foreach($vars as $var){

        $v = $GLOBALS[$var];
        if (!$v){
            return $var;
       }    
    }
    return false;
}  

$value1 = true;
$value2 = false;
$value3 = false;

$vars = array('value1','value2','value3');


/*
// This was the old technique
if (!$value1 || !$value2 ||!$value3){

    return  checkFalseVars($vars);
    // returns 'value2'
}
*/

// This is the new technique:
$falseVar = checkFalseVars($vars);
if ($falseVar !== false) {
    return $falseVar
}

Edit: In one of your comments you mention:

I want get from PHP the information it already knows - which variable was evaluated as false and caused the condition to be triggered.

I want to clarify that PHP does not hold onto information about which comparisons in the if evaluated to true or false. Even though PHP's if statements are doing evaluations to determine if the if statement evaluates to true or false, it doesn't store the results of those evaluations in memory for later use in your code.

Aside from the potential for massive memory consumption if PHP held onto that information, it could also be difficult to work with. An if statement can evaluate much more than just a simple is this variable true or false, and there can be a whole lot of different expression to evaluate.

Some Tips, Tricks, and Common Errors, So we cannot create our own variable or function with a name True — we'll get a syntax error. (Built-in functions are not privileged like keywords: we can define  If a procedure tries to return a null value (for example, using RETURN @status when @status is NULL), a warning message is generated and a value of 0 is returned. The return status value can be included in subsequent Transact-SQL statements in the batch or procedure that executed the current procedure, but it must be entered in the following form: EXECUTE @return_status = <procedure_name> .


You should be able to iterate through your values using a simple FOR loop.

$values = array($value1, $value2, $value3);
for($i = 0; $i < count($values); $i++){
if($values[$i] == false){echo "Value number $i is false.";}
}

This will give you a developer friendly code readout (as in by array which starts at 0.) If you would prefer a more readout which is the same name as your values e.g. $value1, $value2, $value3 - you can make the small change to:

$values = array($value1, $value2, $value3);
for($i = 0; $i < count($values); $i++){
if($values[$i] == false){echo "Value number " . ($i + 1) . "is false.";}
}

I have provided a working ideone example, here: https://ideone.com/cdiatK

eval(), The eval() function evaluates JavaScript code represented as a string. If the argument of eval() is not a string, eval() returns the argument unchanged. the browser to do long expensive variable name lookups to figure out where the Comparison operators · Conditional (ternary) operator · Destructuring  The purpose of the question mark operator ? is to return one value or another depending on its condition. Please use it for exactly that. Use if when you need to execute different branches of code.


Since you asked for the variable name...

function varName( $v ) {
    $trace = debug_backtrace();
    $vLine = file( __FILE__ );
    $fLine = $vLine[ $trace[0]['line'] - 1 ];
    preg_match( "#\\$(\w+)#", $fLine, $match );
    print_r( $match );
}

$value1 = true;
$value2 = true;
$value3 = false;

$values = array($value1, $value2, $value3);
for($i = 0; $i < count($values); $i++)
{

    if($values[$i] == false)
    {
        varName($values[$i]);
    }

}

Dynamic expressions and dynamic variables, When ColdFusion performs dynamic evaluation it does the following: Takes a In this case, the custom tag does not know the return variable name in advance, and gets it as an attribute value. Evaluates a Boolean condition expression. Start studying Computers in Engineering final exam. Learn vocabulary, terms, and more with flashcards, games, and other study tools.


Based on @dustytrash and @rtoyo suggestions I suggested that you could adapt your code this way:

function checkfalseVar(){
    //Use debug_trace() to find the line number that called this function
    $trace = debug_backtrace();
    //Get the contents of the current file.
    $vLine = file( __FILE__ );
    //Get the text of the line of code that called the function
    $fLine = $vLine[ $trace[0]['line'] - 1 ];
    //Use a regular expression to get the list of variable names that were passed as arguments
    preg_match_all( "#\\$(\w+)#", substr($fLine,stripos($fLine,'checkfalseVar')), $match );

    //Loop through each variable name in the argument, to see if that particular argument is null
    foreach($match[1] as $k=>$v){
        // Evaluate if the value of the argument is false; if it is, then return the name.
        if(!func_get_arg($k)) return $v;
    }
    return false;
}

$data=7;
$data2=false;
$data3='';

if(false!==($false=checkfalseVar($data,$data2,$data3))){
      print($false);//output data2;
}

however it may not work in every situations (see why in the comments below).

After further thoughts I found another implementation which is a little more complex and not less consuming but have really more advantages than the first version

function checkfalseVar2(){
    //define a static variable to track function calls in order to allow  search on same line
        static $counter=0;
     //Use debug_trace() to find the line number that called this function
    $trace = debug_backtrace();
    //Get the contents of the current file.
    $vContent = file_get_contents(__FILE__);
    //get all newlines occurrences in order to allow multiple lines search
    preg_match_all('#\n#',$vContent,$newlines,PREG_OFFSET_CAPTURE);
    $i=0;
    $newlineE=$newlines?$newlines[0][$trace[0]['line']+1][1]:0;  
    //found all matches which fit the $trace variable characteristics
    do{
        $newlineS=$newlines?$newlines[0][$trace[0]['line'] - $i][1]:0;
        $sub=substr($vContent,$newlineS,$newlineE-$newlineS);
        preg_match_all('#checkfalseVar2#i',$sub,$match,PREG_OFFSET_CAPTURE);
        $i++;
    }while(!$match[0]);
    isset($match[0][$counter])?$occurrence=$match[0][$counter][1]+$newlineS:$occurrence=$match[0][0][1]+$newlineS;
    //get the list of the functions args as a string
    $signature='';
    $r=$l=0;
    $start=false;
    for($i=$occurrence,$length=strlen($vContent);$i<$length;$i++){
        if($r===$l&&$l!==0&&($l+$r)%2===0) break;
        if($vContent[$i]==='('){
            if(!$start)
                $start=true;
            $r++;
        }

        if($vContent[$i]===')'&&$start){
            $l++;
        }
        if($start)
            $signature .=$vContent[$i];
    }
    //get only parameters as array
    preg_match_all("#\\$(\w+)#",$signature,$parameters);
    $counter++;
    //loop through the values to return the first false ,null or empty occurrence
     foreach($parameters[1] as $k=>$v){
        if(!func_get_arg($k)) return $v;
    }
    return false;//return false if every variables cast to boolean are true
}

with this you could easily do:

$data=7;
$data2=false;
$data3='';
$data4=null;
if(($false=checkfalseVar2($data,$data2,$data3))
    &&$true=
checkfalseVar2(/**/$data4/**/,$data2,$data3)){
      print($false);// output data2 
      print($true);// output data4
}

note that now the function return the name without the dollar sign $ to allow direct use without eval in the code again using for example $GLOBALS[$true] or $$true

However I think you must keep good practices by checking your variable manually because it is really less consuming

if(!$data){...}elseif(...){}else{} 

beacause sometimes it is better to write more do gain more than write less and loose a lot

By writting a new function for this purpose you waste some times, maybe you slow your code a finally you can also consume more memory like in my case so think about it too...

Introduction to Compiler Design, When we evaluate expressions, we need, in addition to the abstract syntax tree of the For terminals (variable names and numeric constants) with attributes, we assume that there Similarly, num has a function getvalue, that returns the value of the number. In a conditional expression, the condition must be a boolean. Variables can refer to measures. Variables can refer to previously defined variables. Columns in table variables cannot be referenced via TableName[ColumnName] syntax. Example. To calculate a percentage of year-over-year growth without using a variable, you could create three separate measures. This first measure calculates Sum of Sales Amount:


Fanuc CNC Custom Macros: Programming Resources for Fanuc Custom , The name “variable' is suggestive enough - variables are storage areas in the upon, for example, by adding two variables together, to get yet another value. The given condition may be checked (some programmers may say “tested' or  The variable name on the left of an assignment statement is the variable that receives the data that results from the evaluation of the expression the right side of the assignment statement. True In an expression using the logical operator ____, as soon as one of the compound conditions is found to be false, no further conditions are tested and


PC Mag, GET mdate VALID <post—condition> The expression on the WHEN clause is evaluated Since the WHEN is evaluated just prior to entering the field, we can use the If we place our “turn on” code in a routine called dstart(), the GET for the date field in F 0xPr0, the VARREAD().function is used to get the variable name. Return Values in SQL Stored Procedure Example 1. In this example, we will show you the default return value returned by the SQL Server. To demonstrate the same, let me execute the previously created Stored Procedure. Please refer to Input Parameters in a Stored procedure article to know the definition behind this stored procedure.


Proceedings of the Seventh ACM SIGPLAN International Conference on , This is a sufficient and necessary condition because , if ez is evaluated in contour k And if e does not get evaluated in contour k , then we can conclude that any value in First , if the variable OL is already empty , then the demand is trivially resulting from the evaluation of er in some contour , gets called somewhere ( at  Return the Index label if some condition is satisfied over a column in Pandas Dataframe Given a Dataframe, return all those index labels for which some condition is satisfied over a specific column. Solution #1: We can use simple indexing operation to select all those values in the column which satisfies the given condition.