The Comprehensive Beginner's Guide to PHP

Posted on - Last Modified on

The word PHP is called a recursive backronym, because nowadays the language is called PHP: Hypertext Preprocessor, which evolved from "Personal Home Page" when PHP first appeared.

PHP was first released in 1995 and it has evolved a lot over the years. While the current stable version is 5.6.X, the community is actively working on PHP 7, which will contain groundbreaking changes and will break the backward compatibility with lower versions of the language. For more details about PHP 7, you can check out this page. WordPress, one of the most widely used CMS systems and blogging platforms, was written in PHP.

PHP code is written inside HTML. As a normal flow, when a new request comes from a Web browser to the Web server, the PHP Preprocessor scans and interprets the PHP code inside HTML before sending the response back to the Web browser.

First, we will configure our development environment and cover some of the basic types of the language. Next, we will check how variables can be declared and used, and how the scope works in PHP. Then we will write some functions and review how to create classes.

Setting Up the Development Environment

To start developing using PHP, a Web server is needed though it's not a must since PHP has a command line interface too. However, the set of features within it is limited. If you are not familiar with Web server configuration, I would advise you to install XAMPP. This package contains Apache Web server, MySQL, PHP and Perl interpreter. After installation, you can navigate to http://localhost and you should see something similar to the screenshot below:


Data Types in PHP

Strings

Strings are one of the most widely-used data types in all programming languages. Strings are a series of characters, series of letters and number, that can be as large as 2GB in memory.

The code below shows different notations of strings in PHP:

<?php
  $name = 'John';

  $question = "How are you today $name?";

  $paragraph1 = "Yesterday we had a great day in the park with the family.
  We had a nice picnic with home made hamburgers and beers. ";

  $paragraph2 = "Last weekend when we were at the forest, the children loved it,
  they were running around having a lot of fun with our dog <em>Nancy</em>."
?>

<DOCTYPE html>
<html>
<head>
  <title>Strings in PHP</title>
</head>
  <body>
    <h1>
      Hi, <?php echo $name ?> !
    </h1>
    <p>
      <?php echo $question ?>
    </p>
    <p>
      <?php echo $paragraph1.$paragraph2 ?>
    </p>
  </body>
</html>

The PHP code block within the HTML code should be put between <?php ?> symbols. The declaration of variables starts with the $ symbol, then the name of the variable. For example, $name is a string variable, where $name is the name of the variable. ‘John’ is the value of the variable in the PHP code.

Strings in PHP can be created using the single quote or with double quotes. You can see the double quote notation for the $question variable. We have the $paragraph1 and $paragraph2 variables which hold multiline strings. Below the PHP code section, we have a normal HTML file declaration with head, title and body elements.

Inside the HTML code, we have embedded PHP code, and in the h1 heading, we have echoed the $name variable. In the first p tag we echoed the $question variable and in the second p tag we echoed the $paragraph1 and $paragraph2 variables concatenated. Once the code is parsed by the PHP Preprocessor, we get the output seen on the screenshot. I mapped the PHP code to the parts of the generated HTML file:

Numbers

In PHP, numbers can be worked with using two types – Integer and Floating point numbers. Integers, depending on the platform, can be stored on 32 bits or on 64bits. The floating point numbers are stored on 64bits, but when using floating point numbers, we should always count with errors. Errors usually arise when we make mathematical operations with float (or double) numbers and start to compare the values. Since in mathematics there are infinite numbers between two numbers—like how we can list infinite numbers between 0 and 1 using decimals--we cannot store an infinite number of values on 64 bits. The compromise is to operate with floating numbers that are precise according to a certain decimal value. In the code below we have a great example for this:

 

<p>
  <?php
  echo "The size of an integer type on this machine is: ".PHP_INT_MAX;
  ?>
</p>


<p>
  <?php
    echo "The size of an integer type on this machine has ".(PHP_INT_SIZE * 8). " bits.";
   ?>
</p>


<p>
  <?php
    $myLuckyNumber = 213737;
    echo "My lucky number is $myLuckyNumber.";
  ?>

</p>

<p>
  <?php
    $myCurrentSalaryIndex =  1.232345535589;
    $myLastYearSalaryIndex = 1.232345435589;
    $errorMargin = 0.0000001;
    $salaryIndexChange = abs($myCurrentSalaryIndex - $myLastYearSalaryIndex);

    if($salaryIndexChange < $errorMargin) {
      echo 'I have the same salary index this year than I had last year.';
    }
    else {
      echo 'My salary index is not the same as last year, the change is: '.$salaryIndexChange;
    }
  ?>
</p>

When the code executes we have the following output:


The PHP_INT_MAX holds the maximum value that an integer variable can hold. On my system, the integers are stored on 64 bits, because my CPU and operating system supports 64bits.

For floating point numbers, we should always have an error margin to compare the elements. In this case, we said that if the difference between the $myLastYearSalaryIndex and $myCurrentSalaryIndex is bigger than 0.0000001, then the text and the value of the change is displayed. We can see that when executing the subtraction, we would expect the difference to be 0.0000001, but because of the issue explained above, we have some extra details in the smaller decimals, which in this case is below E-10.

Arrays

PHP has arrays as a data type. This is not a traditional array as you know it from C or Java. PHP arrays are like maps or hashtables, which contain keys and values. Keys can be strings or integers, and the values can be basically any type from PHP to support the index [] operator. Arrays can be created using the array() function or by the index [] operator.

The code below shows how to create arrays. We sort the array using the sort() method and use the implode() function to generate a string from the array by specifying the separator and the array we want to use to build the string.

<?php
$boys = array("John", "Joe", "David", "Mathew", "Matt", "Dominic", "Robert", "Frank");
$girls = ["Linda", "Hanna", "Eva", "Kim", "Janet", "Cameron", "Lisa"]
 ?>

<p>
  If I will have a <strong>boy</strong>, he will have one of these names:
  <?php
    // lets sort the names
    sort($boys);

    //lets generate a string from the array elements
    echo implode(", ", $boys);
   ?>
</p>

<p>
  If I will have a <strong>girl</strong>, she will have one of these names:
  <ul>
    <?php
      foreach ($girls as $key => $value) {
        echo "<li>$value</li>";
      }
     ?>
  </ul>
</p>

On the screenshot we can see how the PHP code maps to different parts of the generated HTML:

Objects

Support for OOP (Object Oriented Programming) has been available since PHP5, when the type object appeared. Objects can be created with the new keyword. Usually we use the new keyword when we want to create a new instance of a class. PHP supports casting between traditional types, like string to objects, creating a new stdClass instance. In PHP stdClass is the default object.

Now let's see how to declare a new class in PHP:

class Animal {
  public function __construct($name)
  {
    $this->name = $name;
  }

  public function getName()
  {
    return $this->name;
  }
}

Classes can be declared using the reserved class keyword. Every class has to have a name; in this case, our class is named Animal. We have a constructor function, which has to be named __construct in PHP. We pass the name of the animal to the constructor function, which is stored. Using the $this keyword we can reference the class itself. $this always refers to the current object when used in code.

class Octopus extends Animal
{

  public function __construct($name, $nrOfPins)
  {
    parent::__construct($name);
    $this->nrOfPins = $nrOfPins;
  }

  public function hasPins()
  {
    return $this->nrOfPins > 0;
  }

  public function getPins()
  {
    return $this->nrOfPins;
  }

}

$johnny = new Octopus("Johnny", 8);
 ?>


<p>
  <?php
    if($johnny->hasPins()) {
      echo $johnny->getName().", my octopus, has ".$johnny->getPins()." pins.";
    }
  ?>
</p>

 

In this code we created a new class, Octopus, which extends the Animal class. The Octopus class has a constructor and two methods, hasPins() and getPins().

 

We created a new object, called $johnny, and it’s a new instance of the Octopus class. In the paragraph we display the text: “Johnny, my octopus has 8 pins.”

Scope of Variables

The variable scope in PHP can be a tricky one, because the variables’ scope is the context where these were defined. For example, if we declare a variable called $myNumber in our PHP file and we import another PHP file into ours, then $myNumber will be available in the imported file as well. Variables declared within a function have function scope, which means they cannot be accessed outside of the function.

<?php

$myName = 'John Doe';

function countEvens($numbers)
{

  $allEvens = 0;
  for($i=0; $i<count($numbers); $i++)
  {
    if ($numbers[$i] % 2 == 0)
    {
        $allEvens++;
    }
  }

  return $allEvens;
}


echo "Number of even in [1,2,3,4] is ".countEvens([1,2,3,4]);

echo $allEvens;

?>

When we execute this PHP code we get the following output:


We can see that we have an error specifying that we do not have the allEvens variable available.

In some cases, we might want to declare global variables within a function. We can do that using the global keyword. So, if in the code above we would change the function:

function countEvens($numbers)
{
  global $allEvens;

  $allEvens = 0;

  for($i=0; $i<count($numbers); $i++)
  {
    if ($numbers[$i] % 2 == 0)
    {
        $allEvens++;
    }
  }

  return $allEvens;
}

Then the $allEvens variable would be accessible outside of the function too.

In this article, we went through some of the most important PHP basics, like types, variables, functions and classes. These are the building blocks of every application so it's very important to have a good understanding of these.

Posted 2 February, 2016

Greg Bogdan

Software Engineer, Blogger, Tech Enthusiast

I am a Software Engineer with over 7 years of experience in different domains(ERP, Financial Products and Alerting Systems). My main expertise is .NET, Java, Python and JavaScript. I like technical writing and have good experience in creating tutorials and how to technical articles. I am passionate about technology and I love what I do and I always intend to 100% fulfill the project which I am ...

Next Article

Sales technique necessary for freelancers