It’s like any other programming language – you can use only THAT particular programming language to accomplish something. e.g.
<?php
$x = 42; // php variable assignment
alert($x); // javascript function call
This would never work. `alert() is a JS function which (usually) has no analog in PHP, therefore this would die with an undefined function error.
Since PHP can be embedded in other languages, and other languages can be “embedded” within PHP, you HAVE to have clear delimiters between the two, so the compilers can tell where one language ends and another starts. With php, that’d be accomplished by doing an “echo” of the JS code, or “breaking out” of PHP mode:
<?php
$x = 42;
?>
alert(<?php echo $x; ?>);
or
<?php
$x = 42;
echo 'alert(' . $x . ')';
What it boils down to is “context”. If you’re in PHP mode (e.g. within a <?php ... ?>
block, you’re writing PHP code, and any other language you use in there (html, JS) is just plain text as far as PHP is concerned.
If you’re “out” of PHP mode, then you’re in whatever language context the surrounding block is using.
<script>
var x = 42;
<?php // some php code here that causes output />
</script>
In the above case, your “context” is javascript – anything that the PHP causes to be output must be valid in the Javascript context it’s embedded in.
so while
var x = <?php echo 42; ?>;
would work, because 42
is a valid bit of text to have in that particular spot, it would not be valid to have
var x = <?php echo '</script>'; ?>;
That would produce the non-sensical
var x = </script>;
2
solved Embedding JavaScript in PHP [closed]