Get up to 80 % extra points for free! More info:

Lesson 3 - Variables and type system in PHP

In the previous lesson, Installing Apache + MySQL + PHP on Windows and making an app, we installed and prepared everything necessary to program in PHP. In today's lesson, we're going to take a look at the overall basic syntax and work with variables.

Echo()

Let's quickly go over what we covered in the previous tutorial:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>
        <?php
            echo("This text was inserted into a website by PHP");
        ?>
    </body>
</html>

As we already know, a PHP script looks just like a regular HTML website. The main difference being that it has the .php extension, which allows it to contain the <?php and ?> tags (directives). The code within these tags will be executed by the PHP module on the server. The result, generated by the code, will be inserted at that place.

The echo() command prints the given text into the website. Echo() is a function. We write parentheses after the name of every function and enter its input parameters within the parentheses. In this case, the parameter that echo() takes is the text to be printed. Even if the function doesn't require any parameters, you have to include the parentheses (empty ones). PHP is based on functions and it provides quite a lot of them. For the most part, we don't have to make our own functions, we just call a function that PHP provides and have it do what we need. We can also use objects instead of functions, but we won't go into that until later. Bear in mind, that we won't be able to create complex applications without them. This course will be followed by several others that will go into some of the more advanced techniques.

*Note: We can omit the parentheses when using echo(), but you will not be able to do the same thing with most functions. I find it better to use them everywhere rather than have them missing and have the code misbehave.

We pass text to the echo() function through its parameter (in the parentheses). In programming, we call text strings. We declare strings using quotation marks, both single or double. We do that so that PHP doesn't mistake them for other commands. For example, when we write:

echo("echo");

PHP knows that the second echo is text and will print it instead of calling the function. Each command ends with a semicolon. We write commands on separate lines. PHP's syntax is based on the C language, as a matter of fact, PHP itself is programmed in C. Knowing this, you may not be surprised to know that it is very similar to other programming languages that derived from the C language, for example, Java and C# .NET. If you have experience working with any of those languages, you're ahead of the crowd. Either way, we'll explain everything from the ground up.

There are no traces of PHP on the website that the user sees. All that it contains is what was generated by PHP. So users are never able to access or see the PHP code. The HTML website generated by the script above looks like this:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>
        This text was inserted into website by PHP
    </body>
</html>

PHP doesn't replace HTML in any way - it is a tool for generating HTML files based on requests. In most cases, we set up HTML templates into which we add content dynamically. We usually don't know what the content will be until the request is sent as the content changes quite often (e.g. messages in a guestbook). The content is usually loaded from a database.

As some of you may now be saying, " why even bother using PHP if we could make the example above without it"? To put these comments to rest, we will add dynamical functionality to the script.

Variables

You should recall the word "variable" from grade school. For all of you non-programmers - it's a place in the computer memory where we can store data and still be able to work with it later. We can name variables whatever we want as long as we won't add spaces or accent characters. In PHP, We write a dollar ($) sign before every variable.

Let's create a few variables in the PHP part of the website and fill them with values.

$greeting = "Hello";
$age = 15;
$pi = 3.14;

As you can see, I have chosen variable names based on what is stored in them. There is nothing worse than storing an age to variable $a, a greeting to $b, etc.. When you name variables like that, you will end up making the script unecessarily confusing. On the other hand, if you have 2 numbers and you name them $a and $b - you'll be fine. We can easily print the content of a variable using the echo() function. Let's add a couple of more lines to our code:

$greeting = "Hello";
$age = 15;
$pi = 3.14;
echo($greeting);
echo('<br />');
echo($age);
echo('<br />');
echo($pi);
echo('<br />');

You should see the following output:

Your page
localhost/Hello­World

As you can see, we only use quotes for string values. Numbers and/or variable names are written without them.

Data types

Each variable is of a particular type, referred to as data types. In the script shown above, we created variables of the 3 basic data types. The greeting variable is a string, which we have already gone covered. The $age variable is an int which represents a whole number. The $pi variable is a double. You may occasionally encounter the float data type, in PHP, both of these types are the same and represent a decimal number.

PHP is a dynamically-typed language. That means that we don't have to specify the data type of a variable like we have to in languages like C. PHP determines the data type on its own based on the content it is filled with. PHP also automatically converts between types. Theoretically, you wouldn't even have to know that variables have data types. However, you may run into situations where PHP converts variables in a way that you didn't expect, in which case you will need to understand what is happening behind the scenes.

Adding numbers and concatenating strings

As you may have guessed, we can use basic arithmetic, parentheses or other variables when working with numbers in PHP.

$r = 10;
$area = 3.14 * $r * $r;
echo("Circle's area is $area cm<sup>2</sup>");

The output:

Your page
localhost

The code above will create a variable named $r with its value set to 10. We use this value when assigning a value to the $area variable. The value of the $area variable is printed using the echo() function along with some other text.

As you can see, we can easily add variable content into strings, however, it works only with double quotes. If the string was declared with apostrophes (single quotes), it'd be printed as it was declared and the variable won't be inserted. We printed the upper index for cm2 using the HTML <sup> tag. As you may have guessed, the radius would be entered using a form in the visual part of the application. Which we will get to eventually, I promise.

As I said, PHP converts between different data types automatically. Try it out on a couple of different variables:

$a = 10;
$b = "20";
$c = $a + $b;
echo($c);

The output:

Your page
localhost

Although variable $b is text, PHP converts it to a number as soon as it finds out that we want to add it (+) to another number. We'd get the same result even if we did this:

$a = 10;
$b = "20 is my age";
$c = $a + $b;
echo($c);

Although setting it up that way is pretty wild, I just showed you so you could see how PHP handles variable conversions.

We are also able to concatenate strings using the dot operator (.) :

$a = 10;
$b = 20;
$sentence = "Hello, I'm";

$sum = $a + $b;
$concatenated = $a . $b;
echo("Here we sum numbers A and B: $sum");
echo('<br />');
echo("Here we concatenate strings A and B: $concatenated");
echo('<br />');
echo('And one more example: ');
echo($sentence . " " . $b . " years old.");

The output:

Your page
localhost

Based on the program output, you now see the difference between adding numbers and concatenating strings. We're still in HTML, if we want a new line, we add one using the HTML tag for a new line.

I look forward to seeing you all in the next lesson, Strings and arrays in PHP, where we'll introduce you to arrays. Today's exercises can be downloaded from the link below.


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 116x (1.38 kB)
Application includes source codes in language PHP

 

Previous article
Installing Apache + MySQL + PHP on Windows and making an app
All articles in this section
PHP Basic Constructs
Skip article
(not recommended)
Strings and arrays in PHP
Article has been written for you by David Capka Hartinger
Avatar
User rating:
4 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities