2 Printing in the Terminal and on the Web
Let’s write some code!
Open a text editor of your choice to get started. You’ll be saving files with a “.php” extension. To begin you’ll write:
<?php
This signifies that there’s php code after it. If you don’t include this, things won’t work.
To create a variable in PHP, you need to use the dollar sign. PHP isn’t the only language to do this, for example, Perl also prefaces variable names with a special character. Let’s declare a variable.
<?php
$variable;
Now let’s initialize the same variable:
<?php
$variable;
$variable = "string";
One can combine these steps. If we declare and initialize $variable on the same line, our full code will now look something like:
<?php
$variable = "string";
Save your file as example_0.php or something like that. Then in your terminal, type:
>php example_0.php
Absolutely nothing should happen, but there shouldn’t be any errors. It is a working piece of code, but we’ve not told it to display anything. Let’s get it to display to the terminal by adding some more code. We need to add a print statement. Modify your file so it matches this:
<?php
$variable = "string";
print("The value of \$variable is: ".$variable."\n");
There’s a lot going on here. The first thing to note is that the period “.” is like a plus sign for strings. Gluing strings together is called concatenation. The backslash “\” before the first instance of $variable is called an escape character. Without it, the program would print “The value of string is: string” not “The value of $variable is: string” and I wanted to have it print “$variable” literally. Using single quotes would have worked as well but if I had ran:
<?php
$variable = "string";
print('The value of $variable is: '.$variable.'\n');
The “\n” in single quotes would’ve come out as “\n” literally, and I didn’t want that. I included the “\n” to print a new line. In the terminal, this will make things look a lot nicer.
You can very easily print to the web instead and with no modifications to the code that’s already writing to the terminal. Instead of running it with the command:
>php example_0.php
Run:
>php -S localhost:8080 example_0.php
and using a browser of your choice, navigate to: http://localhost:8080/ and you’ll see the message printed in the browser instead of the terminal. How easy was that!?