PHP, or Pre-Processor Hypertext, is a programming language that is used to design web applications and to make a website look more intuitive and interesting. PHP has also gained a lot of popularity over the years as a server-side scripting language. PHP is an easy to use, but powerful, language. PHP works on multiple operating systems and can support multiple servers. All of these features of PHP make it an ideal candidate for a web designing language.
This book will take you through the basics of PHP, including declaring the syntax, declaring and using the variables and data types, operators, and conditionals. It will then cover the principles of building a PHP framework along with building your own PHP web application.
In this chapter, you will begin to learn the building blocks of the PHP programming language. We will be covering the syntax and how to declare and use variables in PHP. We will also look at controlling the execution flow using the if
statement.
By the end of this chapter, you should be able to write simple programs using these elements.
By the end of this chapter, you will be able to:
Use the basic syntax of PHP to write simple programs
Use variables for different data, and manipulate them using different operators
Use conditionals to control the flow of execution
We will start our journey with a look at PHP syntax and executing our first file. Let's begin.
In PHP, syntax is very important; you need proper syntax for your server to know where it should start parsing PHP, and you have to show it via the open and close PHP tags, as shown here:
<?php ?>
Through using the PHP tags, you can add your code just about anywhere in the document. This means that if you have an HTML website, you can just add the tags, along with some PHP code, and it will process. In addition to using the open and close PHP tags, you must also use the .php
extension in your file.
Let's get started with a quick example.
In this section, we are going to use what we've learned so far to display a string to the user:
Open your code editor.
Create a new file and name it
syntax.php.
Enter the following, and save your document:
<?php ?>
Type the following command:
php syntax.php
Switch back to your document and enter the following:
<?php echo "Hello World"; ?>
Go back to the Terminal and type the following:
php syntax.php
You should now see the string, "Hello World" printed on the screen.
To start our learning with PHP, we must first look at the core building blocks that will be used to build every project. In our applications, we will always need a way to store our data temporarily (in our case, we call the storage methods variables).
Variables are defined as follows:
$VARIABLENAME = "VALUE";
As you can see in the preceding example, variables start off using the $
symbol, followed by the name, and the value is assigned using the assignment operator. Here, we have a variable named VARIABLENAME,
with a string value of VALUE
.
Note
Variable names cannot start with numbers or special symbols, besides the $
sign, used to define the variable itself.
PHP is one of the few languages that doesn't require you to declare a data type before assigning a value.
Types |
Examples |
String |
"Hello World" |
Number |
123 |
Float |
1.095 |
Boolean |
TRUE or FALSE |
In this section, we will illustrate a real-world example of using variables in a program. We will start off by creating a variable to store a user's name:
Open your code editor.
Create a new file and name it
variables.php.
Enter the following, and save your document:
<?php $name = "John Doe"; $age = 25; $hourlyRate = 10.50; $hours = 40; echo $name . " is " . $age . " years old.\n"; echo $name . " makes $" . $hourlyRate . " an hour. \n"; echo $name . " worked " . $hours . " this week. \n"; ?>
Enter the following command, and then press Enter:
We will now have a look at the various operators that are available in PHP.
In the section on variables, we saw the = symbol, which, in PHP, is known as an assignment operator. This operator does exactly what the name implies, allowing you to give a variable a value. The first operators are known as comparison operators. Comparison operators allow you to compare two values within a given conditional case.
Inside of the set of comparison operators are the equal, identical, not equal, not identical, less than, and greater than operators.
Usage | Name | Description |
---|---|---|
$a == $b | Equal | TRUE if $a is equal to $b.
|
$a === $b | Identical | TRUE if $a is equal to $b , and they are of the same type. |
$a!= $b | Not Equal | TRUE if $a is not equal to $b . |
$a!== $b | Not Identical | TRUE if $a is not equal to $b , or they are not of the same type. |
$a < $b | Less Than | TRUE if $a is strictly less than $b . |
$a > $b | Greater Than | TRUE if $a is strictly greater than $b . |
$a <= $b | Less Than or Equal To | TRUE if $a is less than or equal to $b . |
$a >= $b | Greater Than or Equal To | TRUE if $a is greater than or equal to $b . |
Up next are logical operators. Logical operators are used to check for multiple cases at one time. The set of logical operators gives you the NOT
, AND
, and OR
operators.
Usage | Name | Description |
---|---|---|
! $a | NOT | TRUE if $a is not TRUE. |
$a && $b | AND | TRUE if both $a and $b are TRUE. |
$a || $b | OR | TRUE if either $a or $b is TRUE. |
In your program, you will sometimes need to do a little math; this is where mathematical operators come in. They give you the ability to add, subtract, multiply, divide, and get the remainder of two divided numbers.
Usage | Name | Description |
---|---|---|
$a + $b | Addition | Sum of $a and $b |
$a - $b | Subtraction | Difference of $a and $b |
$a * $b | Multiplication | Product of $a and $b |
$a / $b | Division | Quotient of $a and $b |
$a % $b | Modulus | Remainder of $a divided by $b |
In this section, we will be extending our previous example to calculate the annual salary of our user. Here we go with the steps:
Open your code editor.
Create a new file and name it
operators.php.
To get started, copy the contents from our
variables.php
document.Now, we will add an additional variable to the document, which will hold the number of weeks:
$weeks = 52;
Next, we will use the multiplication operator to calculate our weekly pay and assign it to a new variable:
$weeklyPay = $hourlyRate * $hours;
Now, with our weekly pay rate, we can calculate our salary:
$salary = $weeks * $weeklyPay;
Our last step is to display our final calculations:
echo $name . " will make $" . $salary . " this year.\n";
Your final document should look like the following:
<?php $name = "John Doe"; $age = 25; $hourlyRate = 10.50; $hours = 40; echo $name . " is " . $age . " years 01d.\n"; echo $name . " makes $" . $hourlyRate . " an hour. \n"; echo $name . " worked " . $hours . " this week.\n"; $weeks = 52; $weeklypay = $hourlyRate * $hours; $salary = $weeks * $weeklyPay; echo $name . " will make $" . $salary . "this year"; ?>
Next, we'll open our directory in our
Terminal
and run the following command:php operators.php
We should now see our data being displayed:
Now that we have a foundation for operators, we can start to use them in what are known as conditionals. Conditionals allow you to control the flow of your program, and they come in the form of if
statements.
A basic if
statement is represented as follows:
if (conditional){ }
Inside of the parentheses, you will hold the condition that is required to activate the code within the curly braces.
Additionally, you can add an else
statement, which will allow you to give alternate code to run if the condition isn't met:
if(conditional){ } else{ }
Note
A helpful function to use with conditionals is the empty
function. The empty
function is used to check whether a variable is empty
In this section, we will be implementing conditionals where we will check the name of the animal and if it matches, we will be printing the sound of the particular animal.
Open your code editor.
Create a new file and name it
conditionals.php.
We are going to start by adding our open and close
php
tags:<?php ?>
Then, we'll create a new function to hold our animal name:
<?php $animal = "cat"; ?>
Now, we can write our first conditional; here, we want to check whether the animal is a cat, and if it is, we will print meow to the user:
<?php $animal = "cat"; if($animal == "cat"){ echo "meow\n"; } ?>
Save the file and open your working directory in the Terminal.
Run the following command, and see the results:
php conditionals.php
Now, we'll expand our conditional a bit further, to add other animal sounds and change our animal to a lion:
$animal = "lion"; if($animal == "cat"){ echo "meow\n"; } else if ($anima == "dog"){ echo "woof\n"; } else if($animal == "lion"){ echo "roar\n"; } else { echo "What does the fox say?\n"; } ?>
Now, let's save it again and run the command in the Terminal; you should get the following result:
Imagine that you are a PHP developer for a department store chain, and the store is preparing for its upcoming Black Friday sale. Staff who work during the sale hours will be given time and a half, as well as a 10% commission on all sales that they make. Additionally, if they make over $1,000 in gross sales, they will earn a $1,000 bonus. Management wants you to create a calculator that makes it easy for the staff members to calculate how much they earned.
The aim of this activity is to help you understand variables and conditionals.
Follow these steps:
Create a new directory and name it
salary_calculator
.Within the new directory, create an
index.php
file.Define the placeholder variables:
<?php $hourlyRate = 10.00; $hoursWorked = 12; $rateMultiplier = 1.5; $commissionRate = 0.10; $grossSales = 25.00; $bonus = 0;
Our next step will be to define our calculations and assign the outcomes to their respective variables:
$holidayRate = $hourlyRate * $rateMultiplier; $holidayPay = $holidayRate * $hoursWorked; $commission = $commissionRate * $grossSales; $salary = $holidayPay + $commission;
Next, we will need to check the gross sales variable to see if the staff member has made over $1,000, to be awarded with a bonus:
if($grossSales >= 1000){ $bonus = 1000; }
Now that we have the default rates and the calculators, we can display the results to our user:
echo "Salary $" . $salary . "\n"; echo "Bonus +\$" . $commission . "\n"; echo "-------------------------------\n"; echo "Total $" . ($salary + $commission) . "\n";
All that a staff member would have to do now is change the value of their hourly rate and gross sales and run the program to get their total pay amount.
We have now reached the end of this chapter. In this chapter, we began with the PHP syntax. We then moved on to variables and the different operators that are used in PHP. Finally, we saw how to implement conditionals and control the execution flow.
You should now have a clear understanding of variables, data types, and conditionals, as well as how they are used together. In the next chapter, you will learn about how arrays and loops are implemented in PHP.