Lesson 3 - Variables and type system in PHP

PHP Basic constructs 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.


 

Download

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

 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
1 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 College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Activities (11)

 

 

Comments

Avatar
HENRY ABUA-ONUORAH:11/29/2016 18:06
very nice
but i tried this code and it is not working
 
Reply 11/29/2016 18:06
Avatar
David Capka
ICT.social team
Avatar
Replies to HENRY ABUA-ONUORAH
David Capka:11/30/2016 2:40

Your HTML code is not valid. You opened the HTML head and didn't close it. You also lack the HTML body. In PHP code, you miss a semicolon right after the $age variable initialization.

I've corrected it for you:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html, charset=UTF-8">
<title></title>
</head>
<body>
<?php
$age=20;
$sentence="Hello,I'm ";
echo($sentence.$age." years old.");
?>
</body>
</html>

Since you use only Notepad, it looks like you didn't read the previous article. Install the NetBeans IDE instead, see https://www.ict.social/…aking-an-app.

Reply 11/30/2016 2:40
You can walk through a storm and feel the wind but you know you are not the wind.
Avatar
 
Reply 11/30/2016 15:30
Avatar
Sumit Kumar
Member
Avatar
Sumit Kumar:23. June 2:15

echo is not function its a language construct.

 
Reply 23. June 2:15
Avatar
David Capka
ICT.social team
Avatar
Replies to Sumit Kumar
David Capka:23. June 3:35

A good course won't bother you with such terms from the start. We can safely state that it's a function and there's no problem with that because there are only a few constructs in PHP which behave exactly the same as functions. The only difference is that you can omit parentheses.

Reply 23. June 3:35
You can walk through a storm and feel the wind but you know you are not the wind.
Avatar
Sumit Kumar
Member
Avatar
Replies to David Capka
Sumit Kumar:26. June 3:48

Okay Sir.

 
Reply 26. June 3:48
To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

6 messages from 6 displayed.