1

Recently I met the below code

did_action( 'init' ) && $scripts->add_inline_script( 'lodash', 'window.lodash = _.noConflict();' );

inside the file \wp-includes\script-loader.php

Does anyone knows what does it mean? Especially double ampersand between two commands. I 've never met this syntax in PHP before and I cannot find documentation about this.

1
  • 1
    This is a PHP question, not WordPress. But && is a bitwise operator. It would be the same as writing if( did_action('init') ) { do_something(); } Apr 19, 2020 at 18:20

2 Answers 2

2

I think its actually not allowed or discouraged in WP coding standards.

Its is basically saying "If true go ahead".

It's a short form of this:

if ( did_action( 'init' ) ) {
  $scripts->add_inline_script( 'lodash', 'window.lodash = _.noConflict();' );
}

You can also think of this as if it's inside brackets of an if statement like this.

$var = false;

if ( $var && $scripts->add_inline_script( '...' ) ) { // As long as $var is false PHP won't execute or check what comes after the `&&`

}

The line itself could be refactored to use AND instead of && as well. This technique is sometimes used to make code "speak" English. Example:

$if_my_value_is_TRUE = TRUE;
$if_my_value_is_TRUE AND print "This get's printed to the screen.";

// The exact same thing with `OR` or `||`
$my_value_is_TRUE = FALSE;
$my_value_is_TRUE OR print "This get's printed to the screen.";
-3

It must be something like :

Do both simultaneously or do nothing

because i find out that if the first command cannot be executed neither the second does

2
  • 2
    It's not. The first statement is always executed no matter what. And it PHP does execute this on order not simultaneously. It needs to know the result of the first function in this case to even decide if to execute the other or not so no, not simultaneously. Apr 18, 2020 at 16:26
  • Instead of answering your own question with what you THINK it "must be" you should accept mine. You even answered your own question with this 1 hour after I answered you. This is not how SO work. Apr 18, 2020 at 17:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.