At this point, we are all set to start our trek exploring the humongous world of PHP, given that its execution environment has been successfully set up.
If you don't have a PHP installation yet on your machine, make sure to go through the previous two chapters (PHP Setup and PHP First Program) to get started with your very first PHP program. The setup is extremely simple, thanks to the XAMPP software bundle.
In this chapter, we'll learn about the basic syntax of PHP, i.e. what are statements, expressions, keywords and so on. We'll also explore how to retrieve input from the user via the CLI. Last but not the least, we'll start performing some arithmetic over numbers — by far, that's the simplest thing to do across all programming languages.
So without wasting anymore time, let's get to work.
Text plays an essential role in computer science.
Many file types are merely text-based; all CLI applications revolve around text; messaging apps transmit text back and forth; complex pattern matching and source codes are all based on text. Just as much important is text to computers is the idea of strings to programming languages.
So what's a string? Well, a string is just a way to represent pieces of text in a programming language.
Defining it formally,
As stated before, in order to distinguish a string (which is just a piece of text) from the rest of the code (which is also just text), we need to have some special characters to indicate the start and end of a string.
In PHP, there are mainly three ways to represent strings, one of which we've already seen in the previous chapter:
- A pair of single quotes —
- A pair of double quotes —
- Heredoc strings (an idea originating from the Unix shell)
There are important differences between all these. The last option will be explored in the PHP Strings unit. For now, let's focus on the first two.
A pair of single quotes (
'') denotes a string as it is. Every character is denoted as it's written inside the pair of single quotes.
Consider the following example:
<?php echo 'Hello World! '; echo 'A newline is denoted as \n.'; echo ' A variable in PHP is denoted as $var.';
In all these examples, notice that whatever we write inside each of the strings is output as it is. There is nothing special inside a single-quoted string — what's there is exactly what we get. Simple!
However, the case is different for double-quoted (
Inside a double-quoted string, certain characters have special meanings. For instance, the backslash (
\) character denotes an escape sequence.
What's an escape sequence?
Certain characters in a piece of text can't anyhow be represented as a single literal graphical character.
For instance, the first letter of the English alphabet can be given in uppercase as
A or in lowercase as
a inside a string. That's great! But what if we want a newline in the piece of text? How do we give that?
Back when computer scientists began working with text, they faced this same challenge. But the solution wasn't something to demand another decade or so. It was pretty ingenious.
Just take a certain character to have a special meaning and then follow that character with another character to, as a whole, denote a special character in the string.
The character chosen to have a special meaning was backslash (
The backslash, paired with another character following it, is collectively referred to as an escape sequence. This other character depends on what we need to denote.
The name 'escape sequence' implies the fact that this sequence of two characters is escaped, i.e. it doesn't appear literally as it is in the string's data.
Shown below are a couple of common escape sequences used in PHP and, in general, all over programming languages.
|Newline (a.k.a. line feed)||Denotes a new line.|
|Carriage return||Take the cursor to the beginning of the current line.|
|Tab||Denotes a tab.|
|Single-quote escape||Denotes the character |
|Double-quote escape||Denotes the character |
Let's try these out.
Suppose we need to make the following output from a PHP file:
Hello World! We are learning PHP.
Just by looking at it, it's clear that the second sentence is on a new line. Hence, we need to use the
\n escape sequence to denote the newline.
Here's the code to output the text shown above:
<?php echo "Hello World!\nWe are learning PHP";
When we run this, we get the desired output. Superb!
Apart from being able to denote escape sequences, double-quoted strings in PHP have one more useful feature which we won't cover right now. It's that of interpolation, i.e. injecting strings within strings. We'll cover interpolation in PHP Strings — Basics.
Moving on, another extremely useful concept involved in strings is that of joining together two strings. Formally, it's known as string concatenation.
To concatenate two strings means to join them together into one single string. In PHP, the concatenation operator (
.) allows us to perform string concatenation.
What is an operator?
An operator refers a symbol or a keyword in PHP that serves to perform a function over one or more given values.
For instance, the concatenation operator, denoted by the dot symbol (
.), serves to concatenate two strings together. Similarly, the addition operator, denoted as
+, serves to add two numbers together.
There is a huge collection of operators in PHP, as we shall see in detail in the PHP Operators chapter later on in this unit.
Consider the code below:
<?php echo "Hello World!" . "\n" . "We are learning PHP.";
Here we're trying to make the same output as before, just this time the messages are separate strings joined together using the
. does is that it joins the given strings into one, hence:
"Hello World!" . "\n" . "We are learning PHP."
"Hello World!\nWe are learning PHP."
It's that simple.
Let's run the code and see the output:
What's more common in programming than numbers?
Numbers are yet another crucial part of computing. In fact, every single thing that happens inside the wires and chips of a computer is a mere computation over numbers that a machine could understand; just that these numbers are different from our decimal system of numbers.
In PHP, working with numbers is extremely easy.
To start off, there are two broad categories of numbers to deal with — one without a fractional part and one with it.
They are known as integers (or integral numbers) and floats (or floating-point numbers), respectively.
An integer, as we all know, is a whole number without any fractional part. Some examples are
9999 and so on.
To denote an integer literally in PHP, we just write it out as it is. For example, consider the following snippet:
<?php echo 10;
Here we have an
echo statement printing the integer
10 on the screen.
Notice how the number isn't wrapped inside quotes. This is because it isn't a string; it's a number (or more specifically, an integer).
Beside integers, the second most important kind of numbers in programming are floats.
Floats, or floating-point numbers, are numbers with a fractional part.
A float is denoted just as we would denote it in normal writing — an integer, followed by the decimal point (
.), followed by the fractional part of the float.
Some examples are
8984564.45468975 and so on.
Shown below are a couple of float literals printed on the screen:
<?php echo 1.05; echo "\n"; echo -90.5;
Notice the second
echo statement here. It's used to add a new line before printing the second float on the terminal.
As we shall see later on in the PHP Data Types chapter, PHP consider integers and floats as separate data types, although at the forefront, they work almost the same way, supporting the same kinds of operations that are explored in the next section.
Let's perform some basic arithmetic operations over numbers.
For addition, we use the addition operator, denoted as
+. For subtraction, we use
-, for multiplication
*, and for division
Besides these four elementary operations, we can even compute the remainder of a division, known as the modulo operation. The modulo operation is carried out by the modulo operator (
%). For instance, the modulo of 5 divided by 3 is 2.
In addition, the exponentiation operation serves to compute the result of raising a given number to the power of another number. It's denoted as
**. For example, the exponentiation of 3 to 4 (i.e. 34) is 81.
Let's try all of these operations on a couple of numbers:
<?php echo 10 + 10; echo "\n"; echo 50 - 20.5; echo "\n"; echo 3 * 6; echo "\n"; echo 10 / 3; echo "\n"; echo 48 % 7; echo "\n"; echo 2 ** 10; echo "\n";
After printing each operation's result, we add a newline in order to make the output clean.
The last two operations work as follows:
48 % 7returns the remainder when
48is divided by
7. The result is
2 ** 10is simply 210 which is equal to
So this was easy.
As in day-to-day math, in PHP, it's also possible to perform multiple operations on numbers in one go.
Consider the following:
<?php echo 10 - 6 * 10 + 2;
What do you think would the output be?
Well let's try it out:
-48 and that's because multiplication is performed before addition and subtraction.
In the language of programming, this is known as operator precedence. The multiplication operator (
*) has a higher precedence than the addition (
+) and subtraction (
-) operators, hence it's performed first.
As in many programming languages, to enforce a certain operation to be done before the other, we can use a pair of parentheses (
()) to group that operation.
Here's the same expression as before, this time with the subtraction being done first:
<?php echo (10 - 6) * 10 + 2;
Recall variables from algebra? Variables in programming represent a very similar idea. They are yet another paramount concept in programming, in addition to strings and numbers.
Let's define a 'variable' precisely:
We can take the container, put anything inside it, and then use the container in place of the value inside it. Later on, we might as well change the value kept in the container.
This 'container' analogy is a useful one when dealing with variables.
However, a more technical and practical definition is in terms of memory that conveys the essential abstraction that variables are in reality.
We can use a variable just how we would use the value stored in it at any place. For instance, if the variable holds an integer, we could add the variable to another integer in the same way that we could add two integers.
With the definition out of the way, let's see how to create a variable.
In PHP, a variable is denoted using the
To create a variable, the
$ symbol is followed by the name of the variable (without any spaces), followed by the
= symbol, followed by the value to store inside the variable. (This is just how we denote a variable in algebra, except for the
Let's see a quick example:
<?php $x = 10; echo $x;
In line 3, we create a variable
$x and assign it the integer
10. This part is often referred to as variable definition — it defines a new variable into the code.
Next up, we echo the variable, just as we would echo the integer
Here's the output.
Simple, isn't this?
Let's consider another example, this time adding
$x and then printing the result:
<?php $x = 10; echo $x + 50;
Reiterating the idea, a variable can be used just how we could use the value it contains. In the code above, we add
50 just like we would add
Moving on, an extremely important thing to note regarding variables in PHP, and in many other programming languages, is that they are case-sensitive, i.e. the variable
$x can't be written as
$X — both of these are completely different variables.
Consider the code below:
<?php $x = 10; echo $X;
When we run it, the program does execute to completion but we don't get any output. In fact, we get some kind of a warning message.
What we have here is formally called a semantic error.
What is a semantic error?
A semantic error is an error in the meaning of a program.
In the code above, there is absolutely no problem in the syntax (grammar) of the program — it's all well-formed. However, there surely is a problem in the meaning of the program — line 4 is trying to echo the value of
$X which is a non-existent variable!
When writing programs, make sure to look for such typos that can lead to semantic errors. But even if somehow a clerical error does make it to the program, PHP makes sure that it comes to our attention by its warning messages.
Moving on, recall that a variable holds a value inside of it. And a variable is itself just a placeholder for a value. So technically, it seems right to say that a variable can be assigned another variable.
Isn't that so?
Well, it's also something we do in algebra. And guess what, this is really possible in almost all programming languages.
In the code below, first we create a variable
$x and assign it the integer
10. Next up, we assign
$y and then finally echo the sum of both variables:
<?php $x = 10; $y = $x; echo $x + $y;
Let's run this code.
As expected, the output really is
20 owing to the fact that
$y is also
Besides printing stuff to the screen, another common action of CLI programs is to obtain input from the user. This is so important that it has a special name — standard input.
So what is it?
When working with PHP in a CLI, as we're doing right now, the standard input is usually tied to input from the keyboard in the CLI application.
To retrieve input from the user in PHP, we use the
fgets() function, passing in the constant
STDIN as an argument.
Wait a second...
Let's first see what exactly is a function.
What is a function?
With the advent of high-level languages, the idea of functions has been introduced to programming. They resemble quite a lot in practice to the functions we deal with in mathematics. However, there surely are some subtle differences.
Calling (or better to say, invoking) a function is the action that leads to the underlying code to be executed. Without calling, the code merely resides in memory and is not executed at all.
Typically, functions are named in order to allow for easily referring to and ultimately calling them. For instance, we could have a function named
sum to add two numbers together.
In PHP, to call a function, we follow its name with a pair of parentheses (
()). Hence, we'd call the
sum function as
Following the idea of functions from mathematics, functions in programming can also have parameters and even define return values.
Parameters are simply extra pieces of information that a function might need in order to perform its computation. For instance, our original
sum function really doesn't make sense without being provided with the two numbers to add. We'll typically call it like
sum(10, 20) to add 10 and 20.
These extra bits of informations are passed inside the pair of parentheses when calling the function (once again, following from mathematics).
The actual values we send into a function when calling it are sometimes also referred to as arguments.
So going with our old
sum function, we can add the numbers
20 by the call
sum(10, 20) (or commutatively as
sum(20, 10)). Here
20 are the arguments we send into the function
fgets()instead of just
fgets. This is done in order to distinguish them from other identifiers.
After performing its computation, a function can return a value. The return value replaces the function's call.
For instance, if we know that
sum() adds the two given arguments together and returns their sum, then the call
sum(10, 20) would be replaced by the value
30 in an expression.
We can use a function call in any expression just like we'd otherwise directly use the return value of that function.
For instance, assuming that the
sum() function is defined, we can add
sum(10, 20) to
sum(10, 20) + 30 to eventually give us
But all this is just a small fraction of the power and potential of functions in PHP!
As we'll discover in the PHP Functions unit, functions can have side effects, be provided with references to given arguments, take variable-length argument lists, count the number of arguments sent to them, save their lexical scope within them, contain functions, return functions, call functions and what not.
PHP is a procedural and functional language and thus enjoys much of the goodness of functions in programming.
So coming back to the discussion,
fgets() is a function that allow us to read data from a given file. A link to the file is provided as the first argument to it.
In order for
fgets() to read data from the standard input (which can also be thought of as a file), the link that we use is stored inside the
STDIN constant provided by PHP.
What is a constant?
As we shall cover in the PHP Constants chapter, a constant is much like a variable in that it's also a storage location to hold given data.
The only difference is that a constant can't be updated once created (hence the term 'constant') and that it isn't prefixed with the
So to read data from the standard input, we write
fgets(STDIN) in PHP.
fgets(STDIN) is executed, a cursor gets displayed in the terminal window (where the PHP script is being run), asking for our input. Once we provide our input and then press the Enter key, the function completes and returns that entered text as a string.
Let's see an example:
<?php echo 'Enter your name> '; $name = fgets(STDIN); echo 'Hello, ' . $name . '.';
Here, we first echo a simple message asking to user to enter his/her name. Usually this is referred to as a prompt message, or simply a prompt.
Typically, prompts end at the
: character to indicate that input is desired (followed by a space for readability).
Coming back to the code, after echoing the prompt, we obtain the input from the user and save the entered value inside the variable
$name. Finally, we say hello to the user by concatenating the strings
$name (recall that
fgets() returns a string).
Let's run this code:
Immediately after running it, a cursor starts to blink right after the
> character, where input is expected to be provided.
Suppose we input the text 'CodeGuage' and then press Enter as shown below:
At this point, the
fgets() function would complete (and be replaced with the string
'CodeGuage') and hence, bring the whole code to completion as well.
Ultimately, the greeting 'Hello, CodeGuage.' would be shown as follows:
Notice one thing in the code above: we group the prompt
echo and the statement calling
fgets() together, i.e. lines 3 - 4, and separate this group from the last
echo statement by an empty line.
Why do you think this might have been done?
Well that's because the prompt
echo statement along with the statement calling
fgets() together represents one single concern, i.e. obtaining input data. The last
echo, on the other hand, is meant to make a greeting and that's a different concern, hence it's kept separate from the previous two statements.
Also notice the fact that the input text 'CodeGuage' has been highlighted and colored blue. This is done in order to distinguish input text from output text in our terminal snippets. From this point onwards, we'll stick to this convention in our course.
Conversion to an integer
fgets() function as we saw above, starts reading input from the standard input stream and returns that as it is. What the function returns, in every single case, is a string.
Having a string at hand won't be an issue if we want to perform string operations on the input data such as concatenation. However, if we want to perform arithmetic over the data, it's better (although not mandatory) to explicitly convert the input string into a number.
For now, we'll just consider converting a string into an integer. In reality, PHP provides programmers with a vast array of conversion functions and constructs to travel between given data types. We shall explore these in later chapters.
So how to convert a string to an integer?
Technically, there are quite a few options — one of them is to use a typecast.
It's represented as a pair of parentheses (
()) between which the name of the data type to cast to is written. The typecast precedes the value to convert.
The typecast that converts a given value to an integer is denoted as
(int). Syntactically, it could be represented as follows:
Let's consider a quick example.
In the code below, we retrieve input from the user via
fgets() and then cast it to an integer in line 6 with the help of the
<?php echo 'Enter an integer> '; $input = fgets(STDIN); $input_int = (int) $input;
$input holds a string whereas the variable
$input_int holds an integer, that is obtained by converting the input string
$input to an integer.
$input_int with a number and echo the result:
<?php echo 'Enter an integer> '; $input = fgets(STDIN); $input_int = (int) $input; echo $input_int * 50;
For brevity, we can even remove the
$input_int variable and directly cast the return value of
fgets() to an integer.
This is demonstrated as follows:
<?php echo 'Enter an integer> '; $input = (int) fgets(STDIN); echo $input * 50;
With time, as you write more and more PHP code, you'll get into this habit of coding with brevity but obviously not at the cost of readability.
The following task is handy in order to get you thinking about this.
Your friend, who is completely new to coding, wrote the following PHP code:
<?php $i = fgets(STDIN); $i2 = (int) $i; $i3 = $i2 % 19; echo $i3;
The idea is to ask the user the input an integer and then output its remainder when divided by 19.
In what ways can the code be improved?
First off, there is no prompt message displayed, describing where and what kind of output is desired. Let's set it up:
<?php echo 'Enter an integer> '; $i = fgets(STDIN); $i2 = (int) $i; $i3 = $i2 % 19; echo $i3;
Next up, the variable name
$i is quite vague. Moreover, there is absolutely no need of casting
$i separately and then storing its result in another variable
$i2, and then storing the remainder in yet another variable
Let's clean up the code:
<?php echo 'Enter an integer> '; $input = (int) fgets(STDIN); echo $input % 19;
Obtaining the input and then typecasting it happens in one statement, while outputting the remainder happens directly in the last
So what do you say, isn't this code much cleaner than what your friend wrote?
Two further optional things that could be done are as follows:
We could leave an empty line before the last
echo statement in order to visually separate different concerns in the code — the first group of statements deals with obtaining the input while the second one deals with printing the input:
<?php echo 'Enter an integer> '; $input = (int) fgets(STDIN); echo $input % 19;
Empty lines significantly improve the readability and logical structure of code. But use them with care — you don't want an empty line after every single line of code!
In addition to this, we could display a message right when the program is run, describing its purpose, as done below:
<?php echo "Compute n % 19\n"; echo 'n> '; $input = (int) fgets(STDIN); echo $input % 19;
Notice how, following the nature of the message 'Computer n % 19', we change the prompt message from 'Enter an integer>' to 'n>'. In this way, the user is able to relate that what is being asked in the input is actually a value for
This last improvement is totally preferential. If you don't want it, no problem; the code is still pretty good to look at.
Statements and expressions
Let's now unravel the secrets to what exactly are statements and expressions in source code.
For example, consider the following code snippet that we created in the previous chapter:
<?php echo 'Hello World!'; ?>
The third line here contains a statement. We can even call it the
It's a unitary piece of code (i.e. taken as one single unit of code) that's executed by the underlying PHP engine as one single instruction.
echo statement is made up of the
echo keyword followed by an expression.
So what is a keyword?
First, let's understand this:
PHP has tons of keywords. It would be a lot to list all of them right now so we'll refrain from that.
Some examples are
interface, and it just goes on and on.
In this course, we'll cover all of these. Yup, that's the level of comprehensiveness offered in the course!
Coming back to
echo, it's a keyword that is followed by an expression, which is resolved down to a value and then finally sent to the standard output.
Time to unravel what's meant by an expression:
'Hello World' in our example is an expression. It evaluates down literally to what it seems to evaluate down to, i.e. the text 'Hello World!'.
Another example of an expression would be
2 + 2.
This expression itself consists of two simpler expressions
2, which merely turn out to be simple literal integers. What this means is that expressions can contain expressions in themselves. In fact, that is often the case.
Moving on, all expressions can act as statements — we formally call these expression statements. However, NOT all statements can act as expressions.
Let's take an example using
First of all, note that the
echo keyword altogether represents a statement. The keyword is followed by an expression. Based on this, if we try using an
echo command as the expression of another
echo, we'd run into an error.
An illustration follows:
<?php echo (echo 'Hello');
The message tells us that PHP ran into a syntax error while parsing line 3.
So what is a syntax error?
What is a syntax error?
A syntax error is an error in the syntax, i.e. the grammar, of a piece of code.
All programming languages have a well-defined and unambiguous set of grammatic rules defining how to write code in them. This holds even for natural languages such as English.
In English, it's invalid to begin a sentence with a period (.); it can only come at the end of a sentence. Similarly, we can't begin a sentence with a lowercase letter. This is what syntax is all about.
In PHP, syntax error are found right when the code is being parsed by the engine (which means that the code still hasn't run). In case such an error is spotted, the engine terminates right at that point, displaying the respective error message — nothing is executed!
Coming back to the code, the reason it fails is simple: PHP expects an expression following
echo but what we have here is another
echo, and because
echo represents a statement in PHP and not an expression, we end up with an error.
This distinction is utterly important to make in these early stages of learning. You should clearly know as to what's a statement and what's not a statement; what's an expression and what's not an expression.
Where PHP expects an arbitrary statement, we can provide any kind of expression — that's because all expressions can act as standalone statements. However, where PHP expects an expression, we can't provide just about any statement. This holds for many other programming languages as well.
Right now, if the distinction between statements and expressions is a bit blur for you, don't worry. Over the course of the upcoming chapters, we'll formally state whether something is a statement or an expression. With time and learning, you'll surely get the gist of it.
Just make sure that you go slowly and gradually, digesting each and every detail as much as you can. If something is unclear, no need to worry, it'll make sense as you proceed through this course.