Search code examples
phpternary

PHP Concatenation to echo script inside of a ternary


I've just started using ternary operators as I feel they really do make my code look neater - however today I've encountered a problem.

I am trying to echo some script tags into my header if a certain request variable is set to true (to reduce http requests for un-needed files), however whenever I try to load my page I get an error:

require_once(./public/lib/functions.js'></script>): 

^ in the above section, why is the browser interpreting the html encoded character, and why do I lose the <script> tag which precedes my require statement?

Here is the code I am using.

echo $ajax_required == true 
  ? "<script src='" . require_once(LIBRADIR . 'functions.js') . "'></script>" 
  : false;

Thanks in advance, Alex.


Solution

  • If its just a .js file and not a .php file, then you might have used directly file name as a string, instead require().

    echo html_entity_decode(($ajax_required == true)) 
      ? "<script src='" . LIBRADIR . "functions.js'></script>" 
      : false;
    

    Note: require() is used to include a .php script inside code, mostly to just re-use your existing code (functions, classes etc).