A second part of learning material for PHP. In this tutorial we'll learn about variables and how to use them.
In a
previous lesson we've learned what PHP is and why we'd want to use it. It's time to start the coding process. This lesson will teach you about the usage of the variables, but first we need to know some general facts. As i've already mentioned in a previous lesson, PHP scripts are used to create a website dynamically. Everything a script outputs is sent to your browser so if it doesn't output anything, you'll receive an epty page. That's why we need to know how to output stuff to the browser. An example that's usually used in all programming languages is called a "hello world" example. So here it is in PHP:
<?php
echo "Hello world!";
?>
If you remember from the previous lesson, PHP code is written between <?php and ?> tags. So everything inside is a PHP script, processed by a PHP interpreter. In the example above we use a PHP's language construct
echo to output text
Hellow world! to the browser. At the end of the line there's a semicolon. Almost all expressions in PHP must end with a semicolon. The text has to be quoted, that means we're outputing text. When you use a textual value in PHP you always have to quote it: the quotes won't be in the output, but it will help PHP to see where your text starts and where it ends, so remember that. A text in programming languages is seen a little differently than we see it in the real world. For example we can easily see a sentence like
John has 10 apples and already know that 10 is a number. Programming languages, however, need to be told where the number is. That's why there's different types of so called variables in PHP as well as other languages. Variables are generally used to store some information. For example you have the sentence
Welcome, my dear user and you know you'll be using it later or you might need to add a user's name to it. That's where variables come in: you can store the text in a variable and then you don't need to access it by writing the full text: you simply write a variable's name. Variables in PHP are defined with a dollar sign before them. Look at the following example:
<?php
$hello = "Hello world!";
echo $hello;
echo $hello;
echo $hello;
?>
In the first line, we've assigned text
Hello world! to a variable, called
$hello. Normally if we wanted to output the same text 3 times, we'd have to repeat the same echo line. But that would make your code difficult to read and ir would be considered a very very bad coding practice. The rule is: if you need to use something more than once - store it in a variable. You don't have to, but you should. As you see in the next lines, when you output a single variable, you don't quote it. When PHP sees this line, it automatically replaces
$hello with its value (
Hello world!). So PHP sees this script as:
<?php
$hello = "Hello world!";
$hello = "Hello world!";
$hello = "Hello world!";
?>
But we see it differently. Actually the example with 3 echoes is also not a good practice, but we're starting from the beginning and we don't know any other methods yet so for now it will do. In some other programming languages there are very strict variable types. Some variables can store only text, some of them - numbers etc. PHP also recognizes that, but it has a much loose typecast. For example you can't assign a text to a numeric variable in some languages, but in php you can assign anything to anything :) Look at the example below to see some different types of variables:
<?php
$str = "This is a textual variable";
$int = 10;
$real = 10.45;
$bool = false;
?>
The lines, starting with // are called comments. Programmers write them to clarify what things do and programming languags simply ignore them. So you are the only one who sees them. You should always write comments in your code, because after some time you'll simply forget how things work. At the end of this tutorial, you'll see an explanation of comments, but for now let's concentrate on the variables. The first one is a so called
string. Strings are variables that contain text. The second is an integer. You can do math operations with integers, but you can't do that with strings. The third one is a float. It's also a number just like an integer, but it has decimal point. Lastly there's a boolean value. This is a special type of value that can only gain 2 values: true or false. Lots of things in coding ending up in true or false so these variables just make your life easier. As you can see, only text variables have to be quoted so let's look at this deeper. As i've already mentioned, the quotes are only visible in the code so that PHP could determine where the text starts and ends. See the example below and read the comments in it:
<?php
$str = Hello world!;
$str = "Hello world!";
$str = 'Hello world!';
?>
So what we've learned from the example above is that we can quote strings in either double or single quotes. And as you can see, there's semicolons after each expression. We don't have to write every expression in a different line, but this helps read your code a lot. Now let's consider the following problem. What if we want to use the text
it's a beautiful day? If we tried to quote this text in single quotes, PHP would see a quote in
it's and, since this is a second quote, it would think the text has ended. And then you'd get an error. So what is the solution to this? There are a few, actuall. First, if you have to use a quote in a string, you can use different quotes to surround the string itself or you could escape the quote and use the same quotes to surround the string. Look at the example:
<?php
$str = 'It's a beautiful ';
?>
The example below shows what you shouldn't do. The same would go for a double quote in a double quoted text. Now let's look at the solutions:
<?php
// This is correct
$str = "It's a beautiful day";
// This is also correct
$str = 'It\'s a beautiful day';
// This is also correct
$str = "This is a \"quoted\" text";
?>
The first solution simply uses different quotes to surround the string. The next two solutions use an escape character. When you use the \ character in a situation like this, it tells PHP to ignore the quote after \. So PHP doesn't count it as a quote. Actually it counts it as a quote, but as a quote in the text, not the surrounding quote. The \ character is removed automatically before any operation with the variable. When you use an escape character, only you see it and PHP doesn't so your text doesn't change from that. Escape character can be used for more things, but for now you just have to know that you can use it to make PHP think that a quote is just a quote and it doesn't tell a string to end. The next thing we're going to learn is simple operations with strings and other variables.
Simple operations with strings
<?php
$txt = 'Some text';
$txt = 'Hello';
$txt = $txt . ', John';
$txt = 'Hello';
$txt .= ', John';
$time_left = 'one day';
$txt = 'Time left: ' . $time_left;
$txt = "Time left: {$time_left}";
?>
The first expression we've already seen a number of times. The next one assigns the
Hello text to the variable, thus deleting everything that was assigned before. The next expression assigns the
$txt variable a value of itself and a text
, John. The dot operator is used to join two texts together. Programming languages don't read the expression from left to right. Instead, they first add
, John to the value of
$txt (which is
Hello) and only then assign this result to the
$txt variable. So as you can see you can assign a variable to itself and even add some other things while you're at it. The next expression is completely the same, except instead of using a dot operator, it uses .= operator. This tells PHP to add anything that's after the .= operator to anything that's before it. The next expression is one way of using a variable in another variable. We've done something like that in a previous expression, that's just another modification. The last expression, however, uses a variable directly in the quoted text. If you surround a variable between { and } while in double quotes, PHP will use it's value instead. You don't need the { and } characters, but it makes the code more readable.
Simple operations with numbers
<?php
$var = 10;
$var = $var + 2;
$var += 2;
$var = $var - 2;
$var -= 2;
$var = $var * 2;
$var *= 2;
$var = $var / 2;
$var /= 2;
$var = $var % 2;
$var %= 2;
$var--;
$var++;
?>
The example itself is pretty explanatory so i don't think there's anything left to say about it.
Operations with booleans
<?php
$var = true;
$var = false;
$var = true || false;
$var = false || false;
$var = false || false || true || false;
$var = true && true && false;
$var = false && false;
$var = true && true;
$var = !true;
$var = !false;
?>
The boolean operations might look mysterios at first glance, but they are really not. For example you can have a situation where you need to greet a user if it is a 22 year female. In this case you will use the AND operator to check if the user is a female and if she is 22 years old. If either of these conditions are false, the entire expression will be false using the AND operator and you will not greet the user. We will talk about this in other lessons. The last thing we'll talk about is variable typecasts. For example, consider the following code:
<?php
$str = 'The value is ' + 5;
?>
You couldn't do this in some other programming languages, because you can't add a number to a string. Don't understand why? Well then imagine if your math teacher asked you to solve this equation:
What would the value of y be? :) Doesn't make sence, does it? The same goes to programming. PHP, however, has loose typecasting so when you use an expression as above, it looks at the operator and sees that it's a plus. A plus operator is used for numbers so, obviously, we need an operation with a numbers. But one of the operands is not a number ... So PHP will convert it to number and add 5 to it. Since this is a simple text, PHP would convert it to zero so the result of this equation would be 5. But in the example below, the result would be 7:
<?php
$str = '2 The value is ' + 5;
?>
PHP, while converting the string to a number, takes all the digits it finds in the beginning of a string and uses them. In this case, there's a number 2. So the result of the entire conversion is 2. 2 + 5 = 7; And now the opposite example:
<?php
$str = 'The value is ' . 5;
?>
As i've mentioned, PHP decides what to do by looking at the operator. And in this case its a text concatenation operator (a dot). So PHP will think that you want to add one string to another and convert the number 5 to a string. And number 5 as a string is still 5, but text this time. So the result will be
The value is 5. These operations are called typecasting. You can also do it manually, by writing the type name in brackets before the value. For example:
<?php
$str = 'This is a string';
(int)$str;
?>
As promised, as a last thing i'm showing the ways to comment your code. There are two:
So learn, have fun and i'll meet you in another tutorial.