Beginning PHP

5 (2 reviews total)
By David Carr , Markus Gray
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies

About this book

PHP is the preferred server-side scripting language for tech giants such as Facebook, Wikipedia, and Tumblr despite full-stack JavaScript gaining popularity with upcoming developers. This is because PHP performs better when dealing with heavy computations on the back end. In this book, you’ll learn everything you need to get up and running with the latest version of PHP, including package management with tools such as composer, secure database operations, and a whole host of other best practices that will help you stay a step ahead of traditional programmers.

Publication date:
July 2018
Publisher
Packt
Pages
214
ISBN
9781789535907

 

Chapter 1. Getting Started with PHP

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

 

The Basics


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.

Using PHP to Display "Hello World"

In this section, we are going to use what we've learned so far to display a string to the user:

  1. Open your code editor.

  2. Create a new file and name it syntax.php.

  3. Enter the following, and save your document:

    <?php
    
    ?>
  4. Open your working directory in the Terminal.

  5. Type the following command:

    php syntax.php
  6. Switch back to your document and enter the following:

    <?php 
         echo "Hello World";
    ?>
  7. Go back to the Terminal and type the following:

    php syntax.php

You should now see the string, "Hello World" printed on the screen.

Variables and Data Types

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

We will now try to implement variables in PHP.

Working with Variables

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:

  1. Open your code editor.

  2. Create a new file and name it variables.php.

  3. 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";
    ?>
    
  4. Open your working directory in the Terminal.

  5. Enter the following command, and then press Enter:

    Note

    Another way to insert a variable's value into a string is to use this special syntax:

    <?php
    echo "My name is ${$name}.";
    ?>

Operators

We will now have a look at the various operators that are available in PHP.

Comparison Operators

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.

UsageNameDescription
$a == $bEqualTRUE if $a is equal to $b.
$a === $bIdenticalTRUE if $a is equal to $b, and they are of the same type.
$a!= $bNot EqualTRUE if $a is not equal to $b.
$a!== $bNot IdenticalTRUE if $a is not equal to $b, or they are not of the same type.
$a < $bLess ThanTRUE if $a is strictly less than $b.
$a > $bGreater ThanTRUE if $a is strictly greater than $b.
$a <= $bLess Than or Equal ToTRUE if $a is less than or equal to $b.
$a >= $bGreater Than or Equal ToTRUE if $a is greater than or equal to $b.

Logical Operators

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.

UsageNameDescription
! $aNOTTRUE if $a is not TRUE.
$a && $bANDTRUE if both $a and $b are TRUE.
$a || $bORTRUE if either $a or $b is TRUE.

Mathematical Operators

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.

UsageNameDescription
$a + $bAdditionSum of $a and $b
$a - $bSubtractionDifference of $a and $b
$a * $bMultiplicationProduct of $a and $b
$a / $bDivisionQuotient of $a and $b
$a % $bModulusRemainder of $a divided by $b

Let's try to use these operators in PHP.

Combining Variables and Operators

In this section, we will be extending our previous example to calculate the annual salary of our user. Here we go with the steps:

  1. Open your code editor.

  2. Create a new file and name it operators.php.

  3. To get started, copy the contents from our variables.php document.

  4. Now, we will add an additional variable to the document, which will hold the number of weeks:

    $weeks = 52;
  5. Next, we will use the multiplication operator to calculate our weekly pay and assign it to a new variable:

    $weeklyPay = $hourlyRate * $hours;
  6. Now, with our weekly pay rate, we can calculate our salary:

    $salary = $weeks * $weeklyPay;
  7. 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";
    ?>
  8. Next, we'll open our directory in our Terminal and run the following command:

    php operators.php
  9. We should now see our data being displayed:

Conditionals

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

Working with Conditionals

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.

  1. Open your code editor.

  2. Create a new file and name it conditionals.php.

  3. We are going to start by adding our open and close php tags:

    <?php
    ?>
  4. Then, we'll create a new function to hold our animal name:

    <?php
    $animal = "cat";
    ?>
  5. 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";
    	}
    ?>
  6. Save the file and open your working directory in the Terminal.

  7. Run the following command, and see the results:

    php conditionals.php
  8. 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";
    }
    
    ?>
  9. Now, let's save it again and run the command in the Terminal; you should get the following result:

Activity: Building an Employee Salary Calculator

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:

  1. Create a new directory and name it salary_calculator.

  2. Within the new directory, create an index.php file.

  3. Define the placeholder variables:

    <?php
    
        $hourlyRate = 10.00;
        $hoursWorked = 12;
        $rateMultiplier = 1.5;
        $commissionRate = 0.10;
        $grossSales = 25.00;
        $bonus = 0;
  4. 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;
  5. 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;
    }
  6. 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";
  7. 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.

 

Summary


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.

About the Authors

  • David Carr

    David Carr has been developing applications for the web using mostly PHP for the past 12 years. He does this for a living and loves what he does as every day there is something new and exciting to learn. In his spare time, the web development community is a big part of his life. Whether managing online programming groups and blogs or attending a conference, he has found that keeping involved helps him stay up to date. This is also his chance to give back to the community that helped him get started, a place he is proud to be part of.

    Browse publications by this author
  • Markus Gray

    Markus Gray is a full-stack web developer/designer with 11 years' experience, based in Philadelphia. He has diverse and deep interests in most trending technologies. He spends most of his time helping public and private companies and has also worked with the federal government in the department of education. Currently, he is the CEO of Syncware Technologies, Inc.

    Browse publications by this author

Latest Reviews

(2 reviews total)
Muito bom.
Very good resource for starting programming with PHP because there's a project based approach in the book, without getting too complex.

Recommended For You

Book Title
Unlock this full book FREE 10 day trial
Start Free Trial