'Is it possible to write javascript function inside of php code?

I mean like

<?php echo "<script> javscript_function(<?php echo "$php_number_variable"; ?>); </script>" ?>

The $php_number_variable would be a number value from other php file.



Solution 1:[1]

Yes that's entirely possible. Basically all that happens here is the value which is echoed by PHP gets embedded in the JS and the whole JS block is then passed to the browser, which runs it - effectively the same as if you'd hard-coded the value instead of echoing it.

The issue you'll have with this specific code is that you can't echo within an echo...instead just concatenate the value into the string you're already building!

e.g.

<?php echo "<script> javscript_function(".$php_number_variable."); </script>"; ?>

Or, since you're using double-quote strings, the variable can be interpolated directly:

<?php echo "<script> javscript_function($php_number_variable); </script>"; ?>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1