This is the first in a series of lessons about PHP (Hypertext Preprocessor) a general purpose programming language used mainly for web development. I am not going to cover the history or installation of PHP. Please refer to the PHP website if you would like to learn more about that. We are simply going to jump in the deep end and start writing code.
I presume you have a text editor you can use (Sublime text, Notepad, VS Code etc.) and a web server you can use on your local machine. Something like Wamp or Xampp for Windows. Linux it comes standard and there is nothing to install. Mac already has PHP installed as well as Apache to test your PHP scripts on. Refer to the installation pages if you have any questions.
Let’s start.
PHP and HTML
PHP is used together with HTML to create interactive web pages. HTML is parsed by the browser, while PHP is parsed by the PHP engine, which is located on a server. PHP is an interpreted language meaning it needs an interpreter to function.
PHP files are files with a php extension and that contains php code.
PHP Code is text written in English and placed between an opening tag <?php and a closing tag ?>. You can also write the tags as <? and ?> but we’ll use the normal <?php and ?>. Anything between the <?php and ?> is considered to be PHP code and will be parsed (decoded, interpreted) as PHP code. Anything not between the two tags will be parsed as HTML
Example:
<h3>This is a heading with HTML tags, parsed as normal HTML</h3>
<?php echo(‘This text will print on the screen, because of the php echo() function’); ?>
You are able to mix normal HTML and PHP anywhere on a page. The file name however must end in .php for it to work.
Example:
<img src=”<?php echo(‘path to file’);?>” alt=”Image alt tag” />
Types
PHP is a loosely typed language meaning you don’t need to declare variables types before you are able to use them. PHP will guess what the type is based on what you used when you created the variable. All variable names start with a dollar sign $. So if you create a variable like this it would automatically become an Integer based on the value you used for the variable
$number = 20
variable = type integer
$name = “George”
variable = type string
There are 8 data types used in PHP:
Booleans
Integers
Floating point numbers
Strings
Numeric strings
Arrays
Iterables
Objects
In our next lesson we’ll discuss each of these types.