get_transient(), PHP switch(), and comparison operators

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:

  1. Which comparison operator (=, ==, ===), in example 2, is ideal for this context?
  2. Which of the following examples is appropriate?
  3. 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.

3 Answers
3

Does it have to use a switch?

why not something like this:

if ( false === ( $value = get_transient( 'value' ) ) ) {
     // this code runs when there is no valid transient set
} else {
    // this code runs when there is a valid transient set
}

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 );

switch( $transient ) :

    case false:
        // transient not set
    break;

    default:
        // transient didnt return false
    break;

endswitch;

Leave a Comment