Blog Post

Excerpt – An Introduction to Programming in PHP: Stomping Zombies with Variables, Loops, Functions and More

Unlike HTML, CSS, and JavaScript, which are processed on the front end (the client computer), PHP is processed on the server (the back end). Rather than making updates once the page has gotten to the client’s computer, like JavaScript, PHP dynamically creates the HTML page on the server, and then sends it to the browser. For instance, instead of having to re-create the navigation in every file, you create it once and pull that information in every time the server builds a page. Adding a top-level page or renaming a top-level page is as simple as editing one file instead of editing every HTML page on your site. You can also run loops and other things that reduce the amount of code you need to repeat. You can even grab content from a database or other data store to make your site even more flexible.

Why Smack Zombies with PHP?

PHP may not be the most contagious young zombie on the block, but many of the most popular websites and content management systems use PHP (including WordPress, Drupal, and Joomla) in their back ends. It will help you write more complex, dynamic web pages while also making maintenance easier and helping you worry less about the tedious parts of building sites with just HTML and CSS. Knowing how PHP works will help you better understand web environments and give you more tools in your toolbox to create and maintain websites.

Designating the PHP Resistance

Because the final output for a PHP file is HTML code, PHP code is often placed in and around HTML elements. In this way, you can work with PHP to generate as much or as little HTML code as you need. But the server needs to know where your PHP code begins and ends. Thus, we need something to designate that. In PHP we use:

<?php Code language: HTML, XML (xml)

to open our PHP code, and

?>Code language: PHP (php)

to close our PHP code. To demonstrate this, I’m going to use the echo command. It just prints some text to the web page.

<p>Zombie Apocalypse says, “<?php echo “Hello World.”; ?></p>Code language: HTML, XML (xml)

The server, when it processes the PHP, will output this:

<p>Zombie Apocalypse says, “Hello World.”</p>Code language: HTML, XML (xml)

And the browser will then show:

Zombie Apocalypse says, “Hello World.”

Try it Out:

https://3v4l.org/PXljm (Make sure you look at the Output tab. To see the HTML rendered, click on the little eye to the far right of the Output label.)

Wait, you say, couldn’t we have just written Hello World, rather than making PHP print it out? That’s correct, but, once we pair this with variables, we’ll be able to print things out that we don’t know when we’re writing the code for the page (e.g., information we get from a database or a page that hasn’t been created yet).