How to Print JavaScript Console Using PHP
On this page, we will illustrate how to use PHP echo for printing JavaScript console. Here, you will find several options for different occasions.
In this snippet, we will demonstrate how PHP echo can be used for printing to the JavaScript console. Generally, it is used for outputting values to the HTML document. Since PHP runs server-side, you can embed a <script> tag within the echo command to output JavaScript that the browser executes client-side.
Below, you can find several examples for different circumstances.
Using the echo Keyword to Display Content
To display content using the <kbd class="highlighted">echo</kbd> keyword, run the following code:
display content with echo keyword
<?php
// Declaring variable and storing the string
$var1 = "W3docs";
$var2 = "A programming portal";
// Use echo keyword to display result
echo $var1 . "\n" . $var2;
?>The output will look like this:
<pre>
W3docs
A programming portal
</pre>
As you can see, the Dot <kbd class="highlighted">(.)</kbd> operator is used to concatenate two strings in PHP. The <kbd class="highlighted">echo</kbd> keyword outputs the values of variables <kbd class="highlighted">$var1</kbd> and <kbd class="highlighted">$var2</kbd> to the HTML document.
So, you can write the JavaScript code in the echo statement, and it will be sent to the HTML document.
Printing a String to the Console
In this section, we will illustrate how to print a string to the console.
Here is an example:
php print string into console
<?php
// Use echo keyword to display result
echo "Open console and check";
echo '<script>console.log("Welcome to W3docs!");</script>';
?>Printing PHP Variable Values to the Console
To print PHP variable values to the console, run the following code:
print php variables value to console
<?php
// Declare variable and store the string
$var1 = "W3docs";
$var2 = "A computer science portal";
echo "Open console and check";
echo '<script>console.log(`' . $var1 . "\n" . $var2 . '`); </script>';
?>What is PHP echo?
Technically, echo is not a function but a language construct. Parentheses are optional and should only be used when passing a single argument.
It is also important to note that echo cannot be used inside expressions or as a function argument.
When passing multiple arguments, do not enclose them in parentheses.