• Hi everyone,

    I’ve been following this tutorial about creating custom meta boxes:

    LINK

    I was wondering if anyone could explain this line of code that uses the ? operator. The code is:

    $text = isset( $values['my_meta_box_text'] ) ? esc_attr( $values['my_meta_box_text'][0] ) : ”;

    I understand what happens if the expression evaluates to TRUE (i.e. if the meta text box has a value), but I can’t understand what happens if the expression evaluates to FALSE. The code after the colon that would be triggered in this scenario is merely: ” (i.e. nothing but a closing curly quote). I would really appreciate it if someone could explain what this code does or what it refers to?! Cheers for any help.

Viewing 4 replies - 1 through 4 (of 4 total)
  • ternary operator
    http://php.net/manual/en/language.operators.comparison.php

    this line:

    $text = isset( $values['my_meta_box_text'] ) ? esc_attr( $values['my_meta_box_text'][0] ) : '';

    translates into:

    if( isset( $values['my_meta_box_text'] ) {
       $text = esc_attr( $values['my_meta_box_text'][0] );
    } else {
       $text = '';
    }
    Thread Starter thescribbler

    (@thescribbler)

    Hi alchymyth,

    Cheers for your reply. I think I understand your code – if the expression evaluates to FALSE then $text is assigned an empty string for a value ($text = '').

    What has me confused about the original line of code is that the code to the right of the colon (that which is triggered when FALSE) appears to be " rather than '' (i.e. a double quote rather than two single quotes).

    Are these two synonymous? Does a single double quote represent an empty string in the way that two single quotes does?

    [EDIT]: I’ve just realised my mistake – it is two single quotes that I’ve just misread from the code as displayed on the tutorial’s webpage. I’ve downloaded the source code and can see that it is indeed two single quotes. Doh! Cheers for you help!

    the code to the right of the colon (that which is triggered when FALSE) appears to be ” rather than ” (i.e. a double quote rather than two single quotes).

    downloaded the source code and can see that it is indeed two single quotes.

    it also sometimes happens that text editors corrupt code, particular quotes of all sorts; and/or that you find this kind of corrupted code in tutorials.

    it is always a good idea to double-check that quotes in code are either the straight double quotes " or straight single quotes '

    Thread Starter thescribbler

    (@thescribbler)

    Yeah, it’s definitely a lesson learned. The code from the tutorial as it is displayed on the website makes the two single quotes appear like a double quote. In future I’ll be sure to download the source code and examine it directly in PSPad to avoid confusion. Cheers for your help.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Question about a statement that uses the ? operator’ is closed to new replies.