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:

Read More
  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.

Related posts

Leave a Reply

3 comments

  1. 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;
    
  2. I think switch is a little to bulky for this. Also your second example is definitely not a way to do it.

    $transient = get_transient( 'foobar' );
    
    if( false !== $transient ) { // boolean false or has no value 
    
        //code goes here
    }
    else { // any other case
    
       //code goes here
    }
    

    === / !== compare by value and type so even if your transient will be integer 0 it won’t be considered false.

  3. 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.