Jump to content

[SOLVED] Beginner question, using if with a variable condition


PNXRMX

Recommended Posts

My site is built up in a weird, complex, but effective way (easy to update, since everything is cross-referenced).

I have a master list set, each item containing many variables. Let's say $a, $b & $c

I want it set up, so that it only includes a particular piece of code if a particular condition is met, for example if $a="Value1" or $c="Value15"

I want to define that condition once per page all items on that page, by setting $condition="'$a'=='Value1'"; or something, and then later using if($condition).

Except that (and many variations on that) doesn't work, and the if statement always returns true. Note: $a is defined after $condition is defined, but of course if($condition) follows the definition of $a. Theoretically, what I am trying to do is possible, all the information is set before it needs to be used.

Does anyone know a solution to this problem? How can I get this to work the way I want?

Simply stated: you want a way to treat stored data as executable code. That's a very useful behavior, but I don't think that it's supported in PHP. What you can do, though, is create a function, give it an input variable, a comparand, and a symbol, and then use a switch() in that function to do what you're after. Something like this:

function variableCondition(mixed varA, string comparator, mixed varB){
    switch(comparator){
        case "==":
            if(varA==varB){
                return true;
                    }else{
                        return false;
                    }
                break;
        <other cases>
    }
}

 

Then, use if(variableCondition($x, "==", "foo")) to do your thing. Untested, hacky and totally without warranty, but it should work.

-Bob

Not sure how that works just yet, but I'll give it a go in a minute. I think I've found a simpler way:

Start the list with

$vartbt="affid";

$reqvarval="pso";

(vartbt=variable to be tested, reqvarval means required variable value)

I want to test the variable $affid to see if it is "pso" or not, if so, include something, if not, don't include something. Also, some pages don't contain conditions, so I want to be able to override the test. On those pages, I set $overridetest=1. I use this code in each item:

if (${$vartbt}==$reqvarval | $overridetest=1) {

include "items/table";

}

Which should translate as:

if ($affid=="pso" or $overridetest=1 -it is not 1 here-) then

include blablabla

Problem is: it always includes, no matter how $vartbt, $reqvarval and $overridetest are set.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.