Forum Moderators: coopster

Message Too Old, No Replies

an alternative to using isset

         

surrealillusions

8:39 pm on Dec 20, 2008 (gmt 0)

10+ Year Member



Hi,

Is there a better of way instead of this way?

Basically, i want to echo a certain phrase on some pages, but not others. Majority of pages wont need this phrase. At the moment, i'm using an isset statement, and setting a variable at the top of the page like $thisVariable = true;

if (isset($thisVariable)) {
echo "phrase 1";
}

Is there a simpler or better way of doing this? Perhaps reading the file name, and if its a certain file name i can add it to a list or something..

if filename = "file1" or "file2" or "file3"
echo "phrase 1"

Would that be a better way? Or is there a way i dont know of yet?

Does any of that make sense? :)

andrewsmd

8:58 pm on Dec 22, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You could possibly check out a switch statement. You could also check them with the or command like you have
if(isset($var1) ¦¦ isset($var2) ¦¦ isset($var3)){
//do some code
}
I'm not really for sure what you are asking with the file thing.

AlexK

10:01 pm on Dec 22, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



No need to use
isset()
in your example, and almost certainly gives the wrong result. As an example, consider:
    $thisVariable = true;
and:
    $thisVariable = false;
and:
    $thisVariable = null;

The test:

    if( isset( $thisVariable )) { 
    echo 'TRUE';
    } else {
    echo 'FALSE';
    }

...will give `TRUE' in the first two cases; only the last will give `FALSE'.

Far better is to always declare ALL variables at the top of your script, and use

isset()
to provide default values. That way, you cannot receive nasty surprises later on. As an example:

    //top of script 
    $thisVariable = $value_from_external_source;
    if( empty( $thisVariable )) {
    $thisVariable = FALSE;
    }
or:
    //top of script 
    $thisVariable = isset( $value_from_external_source )
    ? TRUE
    : FALSE;

The value of both
isset()
&
empty()
is either can be used and, even with the most stringent error-reporting, will never throw an error. The same cannot be said for other tests, which will usually throw a (welcome)
Notice
if the variable has not been pre-set.