Lesson 8 of 28: PHP statements

Operators are one of the most important and basic topics. Almost all expressions somehow contain them. Without PHP operators, it would not be possible to do anything with data in general, just as, for example, in mathematics. Therefore, take this topic seriously, and in the end, be sure to do your homework – only practice, only hardcore.

But before moving on, I suggest exploring the var_dump() function. It allows you to output the type and value of something.

For example, expressions:

<?php
var_dump(5/2);

Result:

float 2.5

Or a variable:

<?php
$result = 2 < 4;
var_dump($result);

Result:

boolean true

2 less than 4. The result is true. That’s right.

Congratulations, now at any moment we can find out what is in a variable, or we can immediately find out the result of an expression. Let’s get back to our main lesson topic.

The topic of operators is very closely intertwined with the topic of data types. As we have already said in the last lesson, the type of data that will result from any expression will depend on the operator. And, for example, the result of addition when using the plus operator will always be a number.

Operator Priority

To begin with, operators have different priorities. As, for example, in mathematics: the multiplication operator will be more priority than the addition operator:

<?php
$result = 2 + 2 * 2;
var_dump($result);

Result:

int 6

Priority can be controlled using parentheses, for example:

<?php
$result = (2 + 2) * 2;
var_dump($result);

Well, here I think everything is clear:

int 8

In general, operator priorities are fairly predictable. The priority of all operators in PHP can be found in the official documentation.

PHP operator types

Now let’s look at the different types of operators.

Arithmetic operators

Here the operators familiar from school are waiting for us:

<?php

$a = 6;
$b = 3;

// Addition
var_dump($a + $b);

// Subtraction
var_dump($a - $b);

// Multiplication
var_dump($a * $b);

// Division
var_dump($a / $b);

// Remainder of the division
var_dump($a % 4);

// Exponentiation
var_dump($a ** 2);

Result:

int 9
int 3
int 18
int 2
int 2
int 36

Many do not understand how the remainder operator works. Everything is simple here. In our case, we calculate the remainder of dividing 6 by 4. It is not completely divisible, the integer part is 1, and 2 is in the remainder. A few more similar examples to understand:

<?php
var_dump(5 % 2);
var_dump(17 % 12);
var_dump(8 % 4);

Result:

int 1
int 5
int 0

I think arithmetic operators no longer require further explanation.

Assignment operator

We have already worked with the Assignment operator. Used to assign a value to a variable.

Classic example:

<?php
$a = 55;

Ok, it’s simple. And what about this:

<?php
$result = ($x = 5) * 2;

Here, the variable $x was assigned the value 5, and then multiplied by 2 and put the result of the expression in the variable $result. Yes, this is also possible in PHP, although it is not welcome, as the code looks rather confusing.

In addition, there are so-called abbreviated, combined assignment operators. For example, in combination with the addition operator:

<?php

$x = 5;
$y = 7;

$y += $x;

var_dump($y);

Result:

int 12

Here:

$y += $x

Could be written as:

$y = $y + $x

Thus, if something is done with the left operand in its original form, then these abbreviated options can be used. And yes, it applies and looks very elegant, you should get used to them now. Let’s look at a few more examples:

<?php

$x = 6;
$y = 3;

$x /= $y;

var_dump($x);

Result:

int 2

And with string concatenation:

<?php

$hello = 'Hello ';

$hello .= 'world!';

var_dump($hello);

Result:

string 'Hello world!' (length=12)

Ok, let’s move on.

Comparison operators

Well, from the name it’s clear what kind of operators these are and what they are for. The result of their work will always be a Boolean value (true or false). Let’s start with the equality or inequality operators:

<?php

$x = 2;
$y = '2';

var_dump($x == $y); // equality test
var_dump($x === $y); // identity verification
var_dump($x != $y); // check for inequality
var_dump($x !== $y); // checking for identity inequality

Result:

boolean true
boolean false
boolean false
boolean true

Let’s explain. The == operator converts the operands to the same type and then compares their values. So the string ‘2’ was converted to a number and the values turned out to be equal.

The identity equality operator === does not perform type conversions and first compares that the types of values are identical, for example, integers, and then compares their values. And if they are the same, then only in this case returns true.

For example:

<?php

$x = 2;
$y = 2;

var_dump($x === $y);

Result:

boolean true

The inequality operator != converts the types to one and compares the values. If they are not equal, returns true, otherwise false.

The identity inequality operator !== first compares the types, if they are not identical, for example, a string and a number, it returns true, otherwise, it compares their values. If they are not equal, returns true, otherwise false.

Comparison operators also include:

<?php

$x = 2;
$y = 4;

var_dump($x > $y); // $x more than $y
var_dump($x < $y); // $x less than $y
var_dump($x >= $y); // $x more or equal to $y
var_dump($x <= $y); // $x less than or equal to $y

Result:

boolean false
boolean true
boolean false
boolean true

Everything is obvious here, we will not linger.

Spaceship

Now consider the comparison operator that appeared in PHP 7. This is a spaceship <=>. Looks like a Star Wars stormtrooper ship, doesn’t it?

The logic of this operator is as follows:

$a <=> $b
If $a > $b return 1
If $a == $b return 0
If $a < $b return -1

Let’s look at an example:

<?php

var_dump(2 <=> 4);
var_dump(2 <=> 2);
var_dump(5 <=> 3);

Result:

int -1
int 0
int 1

This operator was introduced for use in sorting functions. We will not raise this topic, for now, just know that such an interesting operator appeared in the latest version of PHP.

Increment and decrement

Often, different algorithms have to increase and decrease integers by one. There are special increment and decrement operators for this. Options can be very different:

$i++ – postfix increment, returns the current value of $i, and then increments the value by one;
$i– – postfix decrement, returns the current value of $i, and then decreases the value by one;
++$i – prefix increment, first increases the value of the variable $i by one and then returns the result;
–$i – prefix decrement, first decreases the value of the variable $i by one and then returns the result.

Let’s look at a few simple examples:

<?php

$i = 5;

$x = $i++; // First, the variable $x was assigned the current value of $i (5), then $i was increased by 1 (6)
$y = ++$i; // First, we increase the variable $i by 1 (7), then we assigned a new value to the variable $y (7)
$z = $i--; // First, $z was assigned the value $i (7), then it was reduced $i by 1 (6)

var_dump($x);
var_dump($y);
var_dump($z);
var_dump($i);

Result:

int 5
int 7
int 7
int 6

That’s all with increment and decrement. Move on.

Logical operators

Now let’s talk about one of the most important types of operators – logical. These operators are used to calculate conditions. The result of such an operator will always be true or false. In this case, the operands are also true or false. Let’s list them:

&& – logical AND, will return true only if both operands are true;
|| – logical OR, returns true if at least one of the operands is true;
! – NEGATIVE, returns true if the operand is false, and vice versa. It is used if you need to invert a condition, often this is very helpful;
xor – exclusive OR, returns true only if one of the operands is true and the other false.

Let’s look at an example:

<?php

var_dump(true && true); // true
var_dump(true && false); // false
var_dump(true || true); // true
var_dump(true || false); // true
var_dump(false || true); // true
var_dump(!true); // false
var_dump(!false); // true
var_dump(false xor true); // true
var_dump(true xor true); // false
var_dump(true xor false); // true
var_dump(false xor false); // false

And now let’s get more interesting – let’s determine whether the number is even and at the same time it is more than 10. In order to check for parity – just take the remainder of dividing by 2 and compare it with zero. If it is 0, then the number is even. Let’s write the first calculation:

<?php

$x = 14;

$isEven = $x % 2 == 0;

var_dump($isEven); // true

And:

<?php

$x = 14;

$isEven = $x % 2 == 0;

var_dump($isEven); // true

$isMoreThan10 = $x > 10;

var_dump($isMoreThan10); // true

It remains to make sure that both conditions are satisfied. We use the logical AND:

<?php

$x = 14;

$isEven = $x % 2 == 0;

var_dump($isEven);

$isMoreThan10 = $x > 10;

var_dump($isMoreThan10);

$isEvenAndMoreThan10 = $isEven && $isMoreThan10;

var_dump($isEvenAndMoreThan10);

The calculation could be expressed in one line:

<?php

$x = 14;

$isEvenAndMoreThan10 = $x % 2 == 0 && $x > 10;

However, you must admit that the first example is more understandable. I want you to understand. Your code should not take up as little space as possible. It must be understood. It should be easy to read by programmers. In the first case, everything is obvious: they found out that the number is even, that it is more than 10, and decided that both of these conditions are fulfilled simultaneously. Somehow, the person reading your code should think like this.

And yet, if the operands are not Boolean values, they will be automatically converted to true or false.

String concatenation operator

Yes, for strings there is only one operator for combining them into one – the concatenation operator. It is a point and its use is as follows:

<?php

$string1 = 'Hello';
$string2 = 'World!';

echo $string1 . ', ' . $string2;

Result:

Hello, World!

Homework

Read the official documentation on operator priorities. Using the var_dump() function, get the results of the following expressions:

!1
!0
!true
2 && 3
5 && 0
3 || 0
5 / 1
1 / 5
5 + '5string'
'5' == 5
'05' == 5
'05' == '5'

That’s it.

Lesson 7 of 28: PHP data types

Let’s talk about data types in PHP. Speaking of types, we mean the types of values.

Compared to other programming languages (for example, C/C++ or Java), in PHP the same variable can be assigned values of different types. Therefore, in PHP, types should not be assigned to a variable, but to a value. And say, for example, that the variable $var contains an integer value. This is called “dynamic typing” – the same variable can store values of different types. I agree this is very cool.

Let’s look at the following code:

<?php
$var = 123;
$var = 'string';
$var = 3.14;

Here the $var variable on each line changes its value, while these values have different types. In the first case – an integer, in the second – a string, in the third – a fractional number (float).

Strings can be specified using double or single quotes. But there is a difference – in double-quotes, the interpreter will try to find variables, but inside single quotes, no.

Example:

<?php
$var = 123;
echo "Variable value: $var";

This code will display the line:

Variable value: 123

And another example:

<?php
$var = 123;
echo 'Variable value: $var';

Outputs the following:

Variable value: $var

As we can see, the search for variables was not performed inside single quotes and the interpreter returned the text to us exactly as it was defined.

To display the value of a variable and use single quotes, you can “glue” strings together. This technique is called string concatenation (linking). To do this, use the operator “.” (dot) between two values, which is separated by spaces.

Example:

<?php
$var = 123;
echo 'Variable value: ' . $var;

Output:

Variable value: 123

It is worth noting that when using single quotes, working with strings will be faster since there will not be a search (or more correctly parsing) of variables inside the string.

Let’s now look at a code similar to the one we just wrote:

<?php
$var = 123;
$string = 'Variable value: ' . $var;

The variable $string now stores the value of the type “string”. Despite the fact that before that there was an integer in $var. This happened as a result of using the dot operator to concatenate strings. As a result of its use, you will always get a string. And, as you probably already guessed, the type that will result from some expression will depend on the operator. That is, when using the plus (addition operator), a number will always be obtained.

Example:

<?php
$x = 1;
echo $x + '2';

Outputs: 3.

PHP is smart enough to automatically convert the string ‘2’ to a number and perform addition. Thus, depending on the operator, the operands will be first converted to the desired type, and then an operation will be performed. This is called typecasting.

Typecasting can be done independently. This is done using the following construction:

(type_to_be_converted_to) value

Example:

<?php
$string = '123';
$numeric = (int) $string;

The variable $string is now a string, and the variable $numeric is already an integer. So far, we will not dwell on this in detail, but knowing that this is possible will not be superfluous.

Let’s go over the types that we have already examined. These are numbers (integer and fractional), strings. In addition to these, there are several other types of data. We all will not consider them now, but consider another simplest type – boolean (Boolean value). This type can have only two values: true and false. This type is used to test various conditions, and in the next lesson, we will consider its application in more detail. That’s all for types.

Lesson 6 of 28: PHP variables

Today we’ll talk about variables in the PHP. Read below about what it is and how to work with it. Let’s start with the definition.

Variable –  is some value that a particular name corresponds to.

As in mathematics, x = 2 – the variable x is equal to two. Here x is the name of the variable, 2 is its value.

In PHP, variables start with a $ sign. For example: $x.

To assign a value to a variable, use the “=” sign, for example:

$x = 2;

This operation is called – assignment to a variable (or variable assignment).

Of course, the result of the whole expression can also be assigned to the variable. Example:

$sum = 5 + 10;

And then use it:

echo $sum;

We can also use variables inside other expressions:

$x = 2 + 3;
$y = ($x * 2) / ($x + 1);

echo $y;

It is worth noting that variable names in PHP are case sensitive. That is, $x and $X are two different variables.

I would also like to say right away about variable naming. This is one of the most important skills of a good programmer, which beginners at first neglected. So, variables should always be given names that will clearly talk about what exactly is in this variable at the moment.

Examples of good names:

$subscriberEmail = ‘user@email.com’;
$catName = ‘John’;
$dayOfWeek = ‘Wednesday’;

Bad name example:

$result = $b ** 2 - 4 * a * c; // more appropriate name - $discriminant

In addition, there are certain rules that do not affect the performance of the code, but which all PHP programmers adhere to. This makes it easy to read the code of other programmers, and this is very important, since several people always work on large projects, and they must read each other’s code. I repeat, these rules are extremely important, because in the future, when you come to work, your code will be read and changed by other programmers, think about them now. So, we list these rules.

  • The variable name should consist only of English words, and even more so only of the letters of the English alphabet. Not $imraKorta, much less $catname, strictly $catName.
  • The variable name must begin with a lowercase letter, and the following words contained in its name must begin with a capital letter. This style is called camelCase. Not $catname or $CatName, only $catName.

Lesson 5 of 28: PHP expressions

Today we’ll talk about what PHP expressions are. Expression in the PHP language is generally any string, number, object, array, or something else that is presented in explicit form or in the form of any calculations. For example:

'line with spaces'
7
2 + 2
5 / 2

All of the above are expressions. In this case, the expression must have some value. For the examples above, this is, for example, a line with text, an integer 7, an integer 4, and finally a fractional number 2.5.

As you can imagine, expressions themselves are useless until they are used. The whole charm of PHP is that it can be embedded in HTML.
I hope everyone knows what HTML is and know how to work with it. So, PHP can be embedded directly into HTML.

Let’s edit our index.php file. Enter the following code into:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>An example of embedding PHP in HTML</title>
</head>
<body>
<h1>An example of embedding PHP in HTML</h1>
2 + 2 = <?php echo 2 + 2; ?>
</body>
</html>

and look at the result in the browser:

2 + 2 = 4

As we can see, the part of the code that was inside the <?php … ?> was successfully executed. If we now look at the source code of the page in the browser, we will only see the result.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>An example of embedding PHP in HTML</title>
</head>
<body>
<h1>An example of embedding PHP in HTML</h1>
2 + 2 = 4
</body>
</html>

Once again, the PHP code is executed on the server side. In the browser, the client is given only the result. I hope this is clear.

Now let’s see how it works. The web server sees that a file with the .php extension has been requested.

Server understands that there will be code in the PHP language, and transfers the contents of the file to the language interpreter. Interpreter knows that the code is located between the <?php and ?> and as soon as program meets them, then code executes. After that, it gives the result of the execution to the web server, and gives the result to the browser.

An expression, as we have already said, can be represented in the form of calculations. For calculations, in turn, several operators can be used.
We will talk about this in the next lesson.

Lesson 4 of 28: Install and configure PHPStorm

In this lesson, we will look at the coolest IDE for a PHP developer called PHPStorm. This IDE has excellent code highlighting, a bunch of built-in refactoring tools, useful hints, design themes for every taste and more.

This IDE for personal use is worth $89 per year. However, there is an option to use it for free. No, we are not talking about downloading the crack or keygen, the JetBrains themselves offer this opportunity.

Trial version

Software is available to everyone in the form of a trial version for 30 days – here. During this time, you will have time to decide whether you want to buy this software or not.

Purchase

If you are completely satisfied with the product and the proposed price tag is not a problem, then you should thank the developers and buy a subscription. With each subsequent year, the renewal price decreases. There is the possibility of monthly payment. Link to the purchase page – here.

Early Access Programm (EAP)

This option I chose. This is a beta version of the program in which bugs are possible, which will be notified to software developers of JetBrains. But at the same time, you can use it absolutely free. You can download here.

Free access for some individuals

We are talking about students, teachers and developers of free software.

Installation

Download the program and run the installer. Installation is standard and usually does not require any additional steps.

After installation, run the program and open the project that we created in the third lesson. Click:

File -> Open

And select the project folder:

C:\OpenServer\domains\myproject.loc

First of all, you need to set the correct encoding for all files in the project. To do this, go to:

File -> Settings

To the left of the menu, expand the Editor item, and select the File Encodings sub-item. Set the following settings:

Global Encoding: UTF-8
Project Encoding: UTF-8
Default encoding for properties files: UTF-8

Save changes.

Now let’s delete the files that we previously created, which are now encoded in Windows-1251. Yes, the encoding can always be changed in the lower right corner of the program, the change is made for the current open file.

Now let’s create a new file in our project called index.php. To do this, right-click on the www folder in the project structure on the left, select:

New -> PHP File

Enter the name and click Create.

Some PHPStorm features, such as automatic code writing and fast formatting using CTRL+ALT+ L, we will describe during the course, we will make a few more settings for this program.

Lesson 3 of 28: Install and configure OpenServer

Well, itchy hands to install a web server and write the first program in PHP? First of all, go to the official OpenServer website and download the program. I recommend to download the BASIC package, for our needs it will be enough. However, you can see a list of programs that are included in other packages. Perhaps you will find something useful, be it some kind of code editor or GUI client for MySQL DBMS.

So let’s get started. The first step is to download the program itself.

Link to official website: ospanel.io

Installation

We launch the installer and set the directory for installing the program. Installation is a simple unpacking.

After installation is complete, the window will silently close.

Setup

Go to the folder with the unpacked software: C:\OpenServer. Here we see the files to run the OpenServer program for different versions of the system and 3 folders:

  • domains – a folder designed to store your sites. Inside it, we will create our projects, for example: myproject.loc;
  • modules – a folder containing executable files of modules and libraries necessary for their work, additional files;
  • userdata – the folder where the DBMS user data, cache files, logs, and module configuration files are located.

Run one of the exe files in the root, depending on the bit depth of your OS. In my case, this is Open Server x64.exe.

We choose the language and agree with the installation of the necessary libraries:

Reboot the computer. After rebooting, run exe again. An icon with a red flag appears in the tray.

Click on this icon with the right mouse button and select the “Settings” item. The main program window will open. Go to the “Modules” tab and select:

  • PHP version: PHP 7.0
  • Apache version: Apache-PHP-7

Then, go to the “Domains” tab, select “auto search for domains” and select the item with the greatest number of options as the root folder of the domain. You can also add your options here.

Then click “Save” and close the settings window.

Enabling OPCache Accelerator

Remember in the previous lesson we talked about the accelerator? Let’s turn it on. You need to do this in the php.ini file. In order to edit it, right-click on the flag and select the item:

Advanced -> Configuration -> PHP-7

Here you need to remove comments for the lines:

zend_extension="%sprogdir%/modules/php/%phpdriver%/ext/php_opcache.dll"
opcache.enable=1

It should be like this:

Save the file. This completes the configuration.

Hello World

Go to the “domains” folder and create a directory for our project. Let’s call it “myproject.loc”. Inside, create the “www” directory. And inside it is the PHP file “index.php”. Open it and enter the following code:

<?php
echo 'Hello world!';

Now you can start the server and check the script.

If an error occurs when starting the server:

The file C:\Windows\system32\drivers\etc\hosts is not writable

you should close the program and run it as administrator.

The checkbox in the tray should turn green.

Open the browser and go to the address: http://myproject.loc/

Congratulations! Your first (or not?) Program just worked out successfully! We saw the result. And if we now open the page source in the browser, we will see nothing there. The web server gave us the finished result. The user will never see your PHP code. So simple. In the next lesson, we will install and configure the coolest IDE for a PHP developer – PHPStorm. We will also learn how to use it for free.

Lesson 2 of 28: How PHP Works

In this lesson we’ll look at what PHP is, how it works, and what it is for. To begin with, a program written in PHP during its operation is not a standard window that we are used to seeing. In the vast majority of cases, this program runs on the server “invisibly.” That is, we cannot control it at runtime, but in fact we don’t need it.

The fact is that this program should accept a request from the user, take some action, give the user the result, and then exit. And the faster it works, the better. This is the main difference between PHP programs and “standard” programs that constantly hang in memory, wait for user actions and respond to them in real time.

PHP does not work on its own. To work with the user, it must be configured in conjunction with a web server, for example, Nginx or Apache. If in a simple way, then the user sends a request to the web server via HTTP. The web server determines what type of file was accessed, and if it is a file with the .php extension, the web server sends a request for processing by the PHP interpreter, the script is read, converted to byte code, executed and returns a web response to the server. The web server passes the generated result to the user. This result, as a rule, is a dynamically generated HTML page.

This process can be significantly accelerated by connecting an accelerator extension. It is committed to caching the resulting bytecode, and while the file remains unchanged, its execution immediately begins. Starting with PHP 5.6, the OPcache accelerator is included in the distribution by default.

It is worth mentioning why PHP is so good for web development – by default it contains a huge number of tools for working with queries, tools for working with a huge number of databases, and working with files. All this is actively used by modern sites.

You probably already managed to think about the fact that in order to run the program in PHP, you have to tinker with the configuration, because you need to connect it to a web server. Fortunately, there are ready-made solutions that allow you to start a web server with PHP in a few minutes. And modern hosting allows you to upload and run projects in PHP, without thinking at all how everything is arranged there. And this is good, because you are a programmer, not a system administrator. I ask you to accept this, this will allow you to grow as a programmer much faster. Of course, over time you will have to delve into this area, but I ask you not to do this now – devote yourself to programming.

The turnkey solution as a server, which I advise everyone to use, is called OpenServer. But also you can use XAMPP (including a Mac version), WampServer and Web.Developer. We will talk about how to install and run OpenServer in the next lesson.

Download Openserver (yes, it’s for free)

Lesson 1 of 28: Introduction to the PHP Course

For a long time I wanted to post on our site a really good PHP course, after passing which the output will not be regular shit-coders, but people who, with the right approach to learning from the very beginning, will have the base that will give them everything to become professionals.

At first, I could not decide whether to order a course writing, or to do it myself. On the one hand – simplicity for me, but the unknown quality of the product, and on the other – a lot of work, but guaranteed to convey my vision to you.

In the end, it was the goal that arose in my head – to help you become cool PHP developers, that prompted me to create this course with my own brains and hands.

As for my vision of the language – it is this: modern PHP is a very flexible language, in the right hands it allows you to create supported web applications of any complexity.

Facebook, Badoo, Wikipedia – all these giants use PHP.

The productivity of the latest versions has doubled compared to PHP 5.6, now this language is at the stage of very rapid development and improvement.

At the moment, this language is the most popular among employers.

In addition, the language has a very large community and high-quality official documentation translated into many languages. The developer has at his disposal the Composer package manager and the Packagist repository, which contains more than 120 000 packages. And in November 2018, 502 million package installations were made from this repository!

And now about what exactly you should do to get the most out of this course and become a professional in the future. In fact, this is just one action: you should independently try to do homework, which will be attached to the lessons. You do not have to succeed, especially at first. But you should try to do it yourself. And over time, you will surely succeed!

Ready to learn in this way? Then let’s go!

get_term_meta() – get value from taxonomy meta field

This function is used if you need to get some taxonomy meta data. This function works the same as the get_post_meta() function.

get_term_meta ( $term_id, $key, $single )

$term_id
(number) (required) we specify the taxonomy element ID

$key
(string) (optional) we specify the name of the key of the meta field. If the key is not specified, it will display an array of all meta fields of this taxonomy. Default “.

$single
(logical) (optional) can be:

false – returns all values of arbitrary fields with the specified key as an array, this is what I mean:

true – returns the very first value of an arbitrary field with the specified key as a string;

Returns:

if $single is false, then returns an array of values for the specified meta field.
if $single is true, then returns the value of the specified meta field (the very first).

Example of use:

$termini = get_terms( 'category', 'hide_empty=-1' );
 
foreach( $termini as $termin ){
 
echo $termin_meta = get_term_meta( $termin->term_id, 'my_meta_field', true );
 
}

In this example, we passed through the cycle all taxonomies (posts headings) and derived the result for each rubric (category). To get data about taxonomy elements, we used the get_terms() function.

The most important thing! Do not forget to check that your taxonomy has created meta fields, otherwise you will get an empty array. You can add data using simple functions add_term_meta() or update_term_meta().

wp_kses() or how to leave in the text only allowed HTML tags and their attributes

This feature allows you to filter content and leave there only those HTML tags and their attributes that you want.

wp_kses ( $content, $html_tags, $protocols ) ;

$content
(string) (required) the content that you want to filter is placed here

$html_tags
(array) (required) an array listing the allowed HTML tags and their attributes

array(
    'a' => array(
        'href' => array(),
        'title' => array()
    ),
    'br' => array(),
    'em' => array(),
    'strong' => array(),
    'p' => array(),
    'h2' => array(),
    'img' => array(
        'alt' => array(),
        'src' => array()
    )
)

$protocols
(array) (optional) lists the allowed protocols. For example, the following protocols are allowed by default: http, https, ftp, mailto, news, irc, gopher, nntp, feed and telnet.

Returns the filtered text.

As an example, I’ll show the code that filters the content that is displayed using the get_the_content() function. In this example, it was not possible to use the the_content() function, so we used get_the_content() in conjunction with a filter that is embedded in the the_content() function.

$html_tags = array(
    'a' => array(
        'href' => array(),
        'title' => array()
    ),
    'br' => array(),
    'em' => array(),
    'strong' => array(),
    'p' => array(),
    'h2' => array(),
    'img' => array(
        'alt' => array(),
        'src' => array()
    )
);
 
echo wp_kses(apply_filters( 'the_content', get_the_content() ), $html_tags);