Im using a WordPress transient, which expires after an hour, to store a value which is an integer. Im trying to use switch()
and multiple case()
statements to evaluate if the transient exists or not (i.e true or false).
Here are my questions:
- Which comparison operator (
=
,==
,===
), in example 2, is ideal for this context? - Which of the following examples is appropriate?
- Would the following examples yield the same result?
Example 1:
$transient = get_transient( 'foobar' );
switch( $transient ) :
case( true ) :
// do stuff
break;
case( false ) :
// do stuff
break;
endswitch;
versus
Example 2:
$transient = get_transient( foobar );
switch( $transient ) :
case( $transient = true ) :
// do stuff
break;
case( $transient = false ) :
// do stuff
break;
endswitch;
Thanks in advance.
Does it have to use a switch?
why not something like this:
If the a transient returns a value it will not return true. It returns the value of the transient. If the transient is not set then it returns bool(false)
if you are using a switch it would be like this:
$transient = get_transient( foobar );
I think
switch
is a little to bulky for this. Also your second example is definitely not a way to do it.===
/!==
compare by value and type so even if your transient will be integer0
it won’t be consideredfalse
.Your both examples are wrong for the value returned by get_transient. get_transient returns false when the transient is not found, but what if the transient value is 0, it will also evaluate to false.
The PHP switch statement always does the loose comparison, so you might not get the desired results in case when transient value is 0. So its better to not use switch in this case, instead use if.
Though the Example 1 will work if you are sure your transient values will never be something that will evaluate to false.