PHP. Introduction
Tags: beginners, php, tutorial, programming
Published: 2022-08-02 19:10:00

Personally, I hate introduction articles and lessons. It's usually covers really fundamental things which are known by many of us. But I understand that it's still important for those, who just begun learning a new tool. That's why it's here. But to save your time, here's what we gonna discuss in this article...

---

### In this article

- We'll get acquainted with the features of the PHP programming language, areas of application and principles of client-server interaction;
- Find out what data types exist in PHP and how they interact with each other;
- Learn how to use some language functions (`readline`, `echo`, `var_dump`);
- Write and run our first PHP script.

## Theory

### What's PHP?

PHP is an interpreted general—purpose server-side programming language. It is one of the most popular web development tools, for which it was originally created. About 80% of all Internet websites are written on it and this value has not been decreasing for many years. The language is actively developing and new versions are regularly published, but this article series are dedicated to the version of the interpreter 7.4.

#### Where we can apply it?

Despite the fact that most of the Internet sites are written in PHP, the scope of its application is by no means limited to the Web, but it probably best reveals the potential of the language. The language can become a useful tool in the development of automation scripts, deferred tasks, or even as a backend part for a Desktop application.

> **Important!** Considering the main area of application (web development), it is worth noting a very important detail: PHP is a server-side programming language. This means that the code is executed on a remote machine, and not in the user's browser. Therefore, it cannot be downloaded or affected by its operation. This gives certain advantages that determine the reasons for dividing website development into backend and frontend parts.

#### The principle of request processing

To understand as clearly as possible exactly how PHP works and at what exact moment it is used, consider an example familiar to everyone: visiting a web page.

Imagine that we open the browser and enter in the url input: https://dev.to/t/php. At this moment, a request is sent to the server. What is this request? It's says something like: "Server, please give me the content for the page dev.to/t/php". And the server will respond with large and understandable for the browser HTML. To the user, this process usually seems very simple and fast, but, in fact, in the interval between receiving a request and issuing a response, there are a lot of different processes necessary to form the final HTML page. These processes are performed by PHP or another server language.

![Client-Server](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sy5rr2d7j2bwcsfp16j4.png)
 

If you have worked with HTML before, you may have a question, what, in fact, is the difference between the response generated by PHP and the usual request for an HTML document. The difference lies in the dynamism of the data. In the same example with *dev.to*, although it may seem that the data is static and does not change, there is a lot of "magic" performed by the interpreter, for example:

- Fetching information from the database or search engine;
- Getting a translation data;
- Checking whether the user is authorized and with what accesses;
- Fetching discussions and users to follow;
- and so on...

This is just an example of operations that could be performed during our short communication with the server, and they demonstrate the main difference from working with a regular HTML document.

> **Important!** Although PHP was created as a tool for generating dynamic HTML pages, this is far from the only response format available to us in our work. In large modern projects, it is more common to find a situation when small blocks of information in JSON format are returned in response to requests, which are further processed in the user's browser using JavaScript.

#### Types of requests

In the example we considered, we, using a browser, "asked" the server to give us a page at a certain address, but the use of the Internet is not limited to page requests. Very often we need to send some data to the server, for example, a login and password for authorization, or an address for pizza delivery. For such cases, special types of requests are provided, and in order to delve into the understanding of the principle of client-server interaction over the HTTP protocol, let's look at the most common of them:

- GET is the most common type of request, used to get some information. Usually, it depends on the requested URL. Example: you just visit the page dev.to, the browser sends a GET request to display it;
- POST is the next most frequently used type. It is used in cases when we want to send some information to the server. Example: We wrote a comment under a friend's photo. When the "Send" button is pressed, a POST request will be sent with the text of our comment. Just like GET, it relies on the URL, but in addition it very often uses the request body. In the example with the comment, the text we entered under the friend's photo would be passed in the request body.

In addition to GET and POST, the DELETE (deleting information) and PUT (updating data, but often replaced with POST) methods are also very often used, but we will not need them within this article series.

> **Important!** In fact, all HTTP methods support the transmission of the request body, but it is highly discouraged to use such an approach when working with the GET type.

#### What a PHP script looks like

A standard PHP script is a plain text file with the extension *.php. On a computer, it can be opened and edited in any text editor.

The code in such files is very often a mixture of HTML markup with PHP separated by special tags: `<?php` - to indicate the beginning of PHP code, and `?>` to indicate the end.

```php
<body>
    <p>This is the plain and simple HTML part. It will be ignored by the PHP interpreter</p>
    
    <strong>
        <?php
            echo('Everything between <?php and ?> is a PHP code', "\n");
            echo('The interpreter will run it and paste the result here', "\n");
        ?>
    </strong>

</body>
```

If you run this code snippet, the interpreter will execute only the part that is between the PHP tags (`<?php` and `?>`). The rest of the HTML/text will be output unchanged, in the order in which it is in the file.

Thus, the result of processing will be the following HTML fragment:

```html
<body>
    <p>This is the plain and simple HTML part. It will be ignored by the PHP interpreter</p>
    
    <strong>
        Everything between <?php and ?> is a PHP code
        The interpreter will run it and paste the result here
    </strong>

</body>
```

PHP inherits the style of the code from its C-like counterparts. Therefore, after each described instruction, it is necessary to put a semicolon. Otherwise, the code cannot be executed.

It is very important to understand that an interpreter is required to execute PHP code. This means that if you just open the file using a browser, you will see its contents, not the result of execution. For the code to work in the browser, you will need a configured web server. It can be one of many available solutions, for example, Nginx, Apache, PHP-FPM, an embedded PHP server, or even a combination of solutions. You can also execute the code by running it from the command line using the same interpreter. For example, on a Windows computer, you can execute the code with the command `php.exe script.php` where **script.php** – is the name of your PHP file.

> **Important!** In the first several articles of this series, we will run PHP code from the command line, developing console applications/scripts, without affecting the work through the web server for some time. This will allow you to start implementing your ideas and practical tasks much faster.

### Our first PHP script

Now that we have gotten acquainted with what a PHP script is, let's figure out how PHP files are created and how they are run from the command line.

We can use any text editor to write PHP code, but it's highly recommended to draw attention to the one of the IDE's, as **VS Code** or **PHPStorm**.

#### New project with PHPStorm

Launch the IDE and create a new project "PHP Empty Project". Specify any directory convenient for you as the path.

![PHPStorm. New Project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yk08yzqueqoea4ojqs0n.png)
 
After the project is created, pay attention to the area "Project" (By default located on the left side of PhpStorm). Project files are managed in this area. To create a new script, right-click on the project name (in our case, it's PHP_1_1) and select **New -> PHP File**.

![PHPStorm. New php script file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5w7ejgba4lw5jk3qb52m.png)

Enter the script file name and click OK. In fact, when working with PHP from the command line, the file name does not matter at all, but in order to speak the "same language", let's name the file as "script.php".

When the file is created, PhpStorm will automatically open it. You may notice that the PHP opening tag is already present, thanks to IDE for that.
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2womid59ajfvf4834uke.png)
 
#### Running script

There is a solid tradition in the programming world that the first program should be "Hello, world". We will follow this rule.

To do this, in our new file **script.php** enter the following code:

```php
<?php

echo("Hello, world!\n");
```

The entered code should output the message "Hello, world" to the console. A special construction `echo` is used for this. We will get to know it a little later in this article. For now, it's enough to make sure that our code is executed.


Now, to run the script, use the terminal built into PhpStorm. Usually, it can be found at the bottom of the program window, but if for some reason it is not there, you can use the menu **View -> Tool Windows -> Terminal**. In the terminal window that appears, type the following command and press Enter:

```bash
php script.php
```

If all actions are performed correctly, you should see the line "Hello, world!" in the command line.

### Data types

Variables are perhaps the most basic part of any programming language. So let's start our acquaintance with PHP with them.

Variables are a kind of containers capable of storing information of different types. They are used everywhere and in PHP are always indicated by the dollar symbol (`$`) at the beginning.

```php
<?php

$someVariable = 1;
```

Variables can be of different types, and in PHP this is determined by what value they are initialized with. The following types are most commonly used:

* **Bool** or **Boolean** — `true` or `false`, zero or one, signal or no signal. The most basic type that has an analogy in any programming language;
* **Integer** — type for integer numbers. It can contain both positive and negative values;
* **Float** — used when working with floating-point numbers. It can contain both integer and fractional values.;
* **String** — string or character. Allows you to work with text;
* `NULL` — a type indicating the absence of a value;

In addition to the listed data types, arrays, objects, resources and links are very often used, but we will talk about them in the following articles.

When creating a variable, you must follow certain rules:

1. The variable is declared with the dollar symbol ($);
2. It can contain uppercase and lowercase letters, underscores, and numbers in its name;
3. The variable name cannot start with a number.

Also, while working with variables, two simple functions will be very useful to us:

* `var_dump` — outputs the type of the variable, as well as its value;
* `echo` — outputs the value of the variable.

We will talk about functions in detail in the following articles, but for now, the main thing is to know that a function is a specific programming language command that performs any useful actions. To use them, write the function name and parentheses at the end. Don't forget to put a semicolon. 


Values or variables that are inside parentheses are called function arguments. They are needed to specify/transmit the data required by the function to work. `echo` and `var_dump` can take as many arguments as your want, but they require at least one. Here is an example of using these tools:

```php
<?php

echo(100);
var_dump(500);
```

Now that we know how to declare a variable, check its type and value, let's take a closer look at the possible data types.

#### Numbers and its operations

There are many situations when we need to work with numbers. Whether it's calculating the cost of goods in the cart, estimating any probability, or even just working with phone numbers. Numbers surround us, and this makes this type of variable one of the most common.

There are two basic numeric types in PHP: integer (`integer/int`) and floating point (`float`). Declaring them differs only in the value that you pass.

> **Important!** Here and further along the code you can find explanatory lines starting with the double "slash" character ( `//` ). Such lines are comments. They serve solely to give hints or explanations. The PHP interpreter ignores them.

```php
<?php

$someInteger = 5; // Common integer number
$someFloat = 1.5; // A number with a floating point. 
// The only difference they have is the dot in the $someFloat value

// To create float var with "integer" value, we can do:
$anotherFloat = 5.0;

var_dump($someInteger, $someFloat, $anotherFloat);
//int(5)
//float(1.5)
//float(5)
```

Of course, we can perform arithmetic operations on numbers of any type.

To add values, we use plus ("+"). For subtraction, respectively, minus ("-").

```php
<?php
$sum = 50 + 15.4; // float(65.4)
$diff = $sum - 0.4; // float(65)

// But if we work with integer numbers...
$sum = 50 + 5; // int(55) - We get integer as the result
$diff = $sum - 10; // int(45)
```

The asterisk ("*") and backslash ("/") symbols are used for multiplication and division, respectively

```php
<?php

$multiplied = 100500 * 2; // int(201000)
$divided = 100500 / 300; // int(335)

5 * 2.5; // float(12.5)
```

Exponentiation is performed using a double asterisk ("**"), but, most often, you can find an implementation through a special `pow()` function.

```php
<?php

2**10; // int(1024)
pow(2, 10) // int(1024)
```

Another very useful operation applied to numbers is getting the remainder of the division (division modulo). Imagine that you need to determine whether the number is even or not. This can be done by dividing it by 2. If there is no remainder, the number is even, and the remainder is odd. Such operations are performed using the "percentage" operator. It looks like this:

```php
<?php

$even = 26 % 2; // int(0)
$odd = 27 % 2; // int(1)
```

Very often there are cases when we perform some arithmetic operation on the value of a variable, and then immediately write the result of the calculation to the same variable. The code for such situations may look like this:

```php
<?php

$someVariable = 10; // int(10)
$someVariable = $someVariable + 50; // int(60)
$someVariable = $someVariable - 20; // int(40)
```

But it can be optimized using a shortened form of arithmetic operations.

```php
<?php

$someVariable = 10; // int(10)
$someVariable += 50; // int(60)
$someVariable -= 20; // int(40)

$other = 0; // int(0)
$other += 5; // int(5)
$other -= 2; // int(3) 
$other *= 6; // int(18)
$other /= 9; // int(2)
$other %= 2; // int(0)

// We also have a shorter version for +1

$someVariable++; // Same as $someVariable += 1; 
// Or $someVariable = $someVariable + 1;

$someVariable--; // Same as $someVariable -= 1;
// Or $someVariable = $someVariable - 1;
```

#### Strings

Strings are a special data type that allows you to store individual characters, whole sentences of text, or arbitrary character sequences. To create a string variable, initialize it with a value in single or double quotes.

```php
<?php

$newVariable = 'Hello, world';
var_dump($newVariable); //string(12) "Hello, world"
```

An important difference in the approach to working with strings in PHP from other languages is the method of the concatenation of strings. The dot symbol is used for this.

```php
<?php

$name = 'John';
'Hello, my name is ' . $name; // "Hello, my name is John"
```

Strings support control constructs. This means that you can specify, for example, a line break by specifying the sequence "\n" in it.

```php
<?php

echo "We have a city\nto burn";

// We have a city
// to burn
```

Despite the fact that the control construction in this example merges with the word "to", the correct division of the sentence into two lines will occur.

Most often you will have to work with the following types of sequences:

* `\n` – Line break
* `\t` – Horizontal tab character
* `\$` – Displays the dollar sign
* `\”` or `\’` – Outputs a double or single quote character, respectively
* `\\` – Outputs a backslash

Now let's talk about the differences between declaring strings in single and double quotes.

All the sequences discussed above (except for the escaped output of quotes \” and \’) work only when declared in double-quotes. This is the main difference: single ones are used to output strings "as is", without performing any additional processing inside, and double ones support additional string parsing.

In addition to sequences, variables can be used in a string with double quotes.

```php
<?php

$object = 'airplane';

var_dump("$object is the value of \$object variable");
// string(41) "airplane is the value of $object variable"
```

At the same time, if you do all the same actions, but in single quotes, the result will be different:

```php
<?php

$object = 'airplane';

var_dump('$object is the value of \$object variable');
// string(41) "$object is the value of \$object variable"
```

Since the interpreter performs additional computational operations on strings in double quotes, in cases where the string does not contain control sequences or variables, it is worth using a single quote. The reverse situation will not cause any errors and warnings, but this rule is very often used in professional development.

#### NULL

Null is both the type and the only value of this type. Means no value. A variable gets null as a value in only three cases:

* When it is explicitly set to null (`$variable = null;`);
* When a variable is created, but the value has not been set;
* When the variable is not created or deleted.

This type can be useful when working with functions. We'll get to know them later, but for now, it's just important to understand what null is and where it comes from.

#### Type cast

PHP is a dynamic typing language. This means that the interpreter tries to perform self-automatic type conversion in those situations when it is required. Example:

```php
<?php

$stringNumber = "150";
$integerNumber = 75;

var_dump($stringNumber + $integerNumber); // int(225)
```

In this example, we are trying to add an integer 75 with a lowercase 150. Perhaps this is due to dynamic typing. PHP understands that actions are performed on numbers (remember, we use the dot symbol to add strings. If there is a "+" symbol here, then we add up the numbers) and converts the string "150" into a regular number.

This also works in the opposite direction. If we replace the addition operation with string concatenation, we get a different result:

```php
<?php

$stringNumber = "150";
$integerNumber = 75;

var_dump($stringNumber . $integerNumber); // string(5) "15075"
```

We can perform such transformations not only in the context of operations but also independently in arbitrary places of the code. This transformation is called a custom. This is done as follows:

```php
<?php

$floatVariable = 5.16;
$integerVariable = (int)$floatVariable; // int(5)
(bool)$floatVariable; // true
(string)$integerVariable; // string(1) "5"
```

Despite the fact that the language performs a lot of transformations and makes development quite simple and fast, try not to rely too much on dynamic typing. This does not mean that it is necessary to cast all variables, but try to avoid moments when, for example, you had a variable with a value of type bool, and you overwritten a string into it. The stricter your approach to the code, the higher your skills will be valued.

#### Boolean

The simplest and most common type is Boolean or bool. It is used to express truth and can contain only two values: `true` and `false`.

A variable of this type is declared, as usual in PHP, simply by setting the required value:

```php
<?php

$someBoolean = true;

var_dump($someBoolean); // bool(true)
```

Similar values, like any other logical expressions, can be inverted – converted to the opposite. To do this, use the exclamation mark symbol at the beginning of the expression.

```php
<?php

$someBoolean = true; 

var_dump($someBoolean); // bool(true)
var_dump(!$someBoolean); // bool(false)
```

In addition to explicitly declaring a value, numerical comparisons can be applied:

```php
<?php

$number = 5;
$number > 10; // Will be true, if $number value greater than 10. Else it will be `false`. In this case - false
$number <= 5; // true, if $number value less than 10 or equal to it.
// In this case it's true
$number < 5; // false
$number >= 2; // true
```

Also we can perform equivalence reconciliation. To do this, a special operator is used — double equal sign (==). In cases where the values are the same, we will get true in the result, otherwise false.

```php
<?php

$isEqual = 5 == 5; // true
5 == 4; // false
false == false; // true
true == !false; // true
```

Of course, if there is an equivalence comparison (equality of values), there is also a check for their difference from each other. To do this, an inverted version is used, consisting of the characters exclamation mark and equals (!=). Consider a usage example:

```php
<?php

true != false; // true
2 + 2 != 5; // true
2 + 2 != 4; // false 
```

> **Important!** Double equals is a "soft" equivalence check. Therefore, if you, for example, compare the number 5 and the lowercase value "5", you will get "true" as a result. This happens because PHP tries to bring the values to a single type and turns the string "5" into a regular number and compares them already. If you want to make a strict comparison involving type checking, use triple equals (===).

```php
<?php

var_dump(5 == "5"); // bool(true)
var_dump(5 === "5"); // bool(false)
var_dump("false" == true); // bool(true) 
```

Pay special attention to the last example "false" == true. The result of such a comparison is true, all for the same reason. PHP tries to convert the string value "false" to a Boolean type and gets true as a result. Therefore, in the end, the comparison looks like true == true.

### User Interaction

#### Data output to the console

We have already got acquainted with the `echo` function and you may have noticed that in some cases we do not call it a function, but a construction. This is an important feature of `echo`, which allows you to use it not only with parentheses, but also without them

```php
<?php

echo("Hello, World\n");
// can be replaced with
echo "Hello, World\n";
```

The second version of the record is used much more often. In the following examples, we will use exactly this option.
In addition to `echo`, PHP provides another output function to the console — `print`. The method of using it is very similar to the functional style of echo:

```php
<?php

print("Hello, World\n");
```

There are some differences between these two tools, despite their similarity:

* `echo` can accept any number of arguments for output, `print` accepts only one;
* `echo` does not return any values, while `print` always returns `1`. Now it may seem pointless, but in future articles we will analyze examples where such behavior is more convenient.

It is important to note that the difference between `echo` and `print` is often asked as a question in interviews.

#### Handling the input

It is very useful to output information to the user, but in order to achieve greater flexibility and dynamism of the code, we will often need to receive data from it.

In order to get user input from the command line, the `readline` function is used. As an argument, you can pass it the text that will be displayed before reading the input. It is used as follows:

```php
<?php

$someVariable = readline("What's up?\n");
```

The `readline` function will read user input until the Enter button is pressed. To consolidate this knowledge with practice, let's rework our script so that it asks for the user's name and greets him. To begin with, we will output a greeting and ask for a name.

```php
<?php

$name = readline("Hey, what's your name?\n");
```

A line break at the end of the greeting is not required, but thanks to it, interaction on the command line is perceived more comfortably. 

When the user enters the name and presses Enter, we will get it into the `$name` variable and can use it anywhere. If the name is not entered (the user immediately pressed Enter), we will get just an empty string. For now, we will not make any safety nets and just output a personalized greeting.

```php
<?php

$name = readline("Hey, what's your name?\n");
echo "Glad to meet you, $name\n";
```

Now let's run our script. Enter the startup command again in the terminal:

```sh
php script.php
```

Please note that the program, having reached the processing of the `readline()` function, will stop and continue execution only after receiving a press on Enter from the user in the console.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yw2x1xil62pokvjqzl2n.png)

## Practice 

1. Implement a script to run from the command line. When running, the script should ask the user for his name, and after receiving the answer, ask a question about his age. After receiving all the necessary data, output the result in the following form: "Your name is your {NAME}. {AGE} years old"

2. Refine the script implemented in the previous task as follows: Replace the age question with a chain of interviews about important things planned for the day (three tasks). The program asks: "What task you 're facing today?". The user responds with text and presses Enter. The next question of the program is: "How long will this task take approximately?". The user responds with a number and presses Enter. Note that the number of tasks is strictly limited in the code and is equal to three. The probability of entering incorrect values in this task is ignored. After three questions , the result is displayed as follows:

```
John, you have 3 tasks planned for the day:
- Walk with the cat (1h)
- Drink coffee (2h)
- Lie on the couch (4h)
Approximate execution time of the plan = 7h
```