Outputting two variables in php. First PHP Lesson: Syntax Features, Data Output, Variables, Error Handling

Last update: 1.11.2015

Like many programming languages, PHP has variables. Variables store individual values ​​that can be used in PHP expressions. The dollar sign $ is used to denote variables. For example,

A variable is defined here that will store the number 10. The value is assigned using the equals sign = .

You can assign a value to another variable:

$a = 10; $b=$a; echo $b;

PHP is a case-sensitive language, which means that the $counter and $Counter variables will represent two different variables.

Also, when naming variables, we need to consider the following rules:

    Variable names must start with an alphabetic character or an underscore

    Variable names can only contain characters: a-z, A-Z, 0-9, and underscore

    Variable names must not include spaces

Checking for the existence of a variable. isset statement

If a variable is declared, but it is not initially assigned any value (in other words, it is not initialized), then it will be problematic for us to use it. For example:

When trying to display the value of a variable, we will get a diagnostic message that the variable is not defined: Notice: Undefined variable: a in C:\localhost\echo.php on line 3.

The isset() statement allows you to determine whether a variable is initialized or not. If the variable is defined, then isset() returns true . If the variable is not defined, then isset() returns false . For example:

To test the variable, the if...else construct was used, which determines the truth of the expression. And if the expression is true, then the expression after the if block is executed. If the expression is false (that is, it is equal to false), the expression after the else block is executed.

Here the variable is not initialized, so the isset($a) statement will return false , and hence the else block will fire. If we were to assign some initial value, for example, $a=20 , then the isset statement would return true , and the browser would display its value.

With the help of an operator unset() we can destroy the variable:

Surely you have a closet or chest of drawers at home. The principle of their use is simple: we put things there that we do not need right now, but may be needed after a while.

Variables are arranged in exactly the same way. You can put some value in them and store it there until you need it.

Creating Variables

You can put a value in a variable like this:

In the code above, we created the $name variable and put the value Ivan into it, then we created the $age variable and assigned the value 20 to it.

The name "variable" means that its value can change during script execution:

In some languages, a variable must first be "declared" before being used. There is no declaration in PHP - a variable is created the moment you put a value into it.
However, PHP programmers often say "declare a variable" instead of "create a variable".

Also instead of "put in variable value" is often said to "assign a value".
The reason is simple - the symbol = , thanks to which we store the value in a variable, is called the "assignment operator". Hence the term "assign".

Variable naming conventions

1. The variable name begins with the $ symbol.

2. The second character can be a letter or an underscore _

Variable names are case sensitive. $name and $Name are different variables.

Displaying the value of a variable on the screen

You can display a variable using the echo command already known to us:

The echo command allows you to display multiple values ​​at once:

Note that we passed 2 values ​​to echo, separating them with a comma. So we can pass as many values ​​as we want. The following two examples will produce the same result:

Also in PHP there is a shorthand syntax for outputting variables. Instead of

Prior to PHP 5.4, the shorthand syntax only worked when included in PHP settings the short_open_tag directive, which also allows you to use a shortened opening tag

Checking the value of a variable

The echo command is not always convenient for checking the current value of a variable. For example, if you try to display an empty string "" absolutely nothing will be displayed on the screen. And it is not clear what the reason is - in an empty variable or non-working code.

Therefore, the var_dump() function is used to check the value of a variable:

Result of script execution:

String(5) "Vasya" string(0) ""

As you can see, PHP outputs not only the contents of the variable, but also the number of characters, and even the type of the variable (string). We will look at data types in detail in the next lessons.

Removing variables

You can remove an existing variable using the unset() function:

And now it's time to practice a little.

Remember, almost any PHP problem can have multiple solutions. Therefore, if your decisions differ from those written on this site, this does not mean at all that you have done something wrong.

Write a script that:
1. Creates variables named title and content and some values.
2. Displays the value of the title variable inside the h1 tag, and the value of the content variable inside the div tag.

Show Solution

", $title, ""; echo "

", $content, "
"; ?>

I want to once again draw your attention to the fact that this decision is not the only correct one. For example, following code will lead to the same result:

I decided to write this article in order to dot the right way and when to display data. The article is not simple, so if you have never displayed text before, then it’s better to start with the first lesson of the PHP course, and as you gain experience, then look here.

To display text on the screen, we use one of the following language constructs: echo or print, or the printf function. Let's take a look at the options and their features:

The printf function allows us to print formatted text to the screen:
printf("%%b = "%b"", 322); // Display value in binary representation

Printf is used very rarely, the most popular use is to convert the price of a product to the classic form: rubles.kopecks. For example:

If printf is used very rarely for output, then here are the print and echo language constructs - in every code! I say that the printf function and value should be written in brackets according to the example above, but echo and print - language constructs and text should not be written in brackets:

There is a difference between echo and print, although they have the same meaning. print can only indicate 1 value, but in echo you can list them separated by commas:

Despite this, it is still possible to output 2 variables through one print and this is done using concatenation:

String concatenation works like this, it FIRST combines everything into one big string, and only then outputs once! On the other hand, we do not say in turn "print this, print that", we say: you have 1 byte allocated in memory for $x, and 1 byte for $y, combine $x and $y in memory and get another temporary a string of 2 bytes (2 Latin characters), and then print and clear the memory. As a result, mathematicians have already been able to calculate. that when concatenating, 4 bytes will be temporarily occupied for data, and when listed with a comma, only 2.

At first glance, it seems that the comma is still cooler in this case, but everywhere the dot is used everywhere. In fact, the answer is very simple and any expert will confirm it - there is no point in bothering and saving on matches, the use of a dot is considered more classic and a matter of habit for many, and you will never in your life encounter the fact that the site is faster or slower because of the dot or a comma. The real performance of sites lies in completely different issues (complex operations, large amount of data in the Database)! Therefore, feel free to use what you have previously used, there is no point in relearning.

Regarding concatenation, it is worth noting the most important and huge thing - it is used to combine a variable with a variable or a string with a variable, but concatenating a string with a string will be considered bad form:
hello

World
"; // many tags can fit in one line for output, feel free

But there is one small feature, when we need to use double quotes for special string processing (more on that later), then we apply string concatenation:

Concluding the topic of print and echo, I would like to clarify the second difference. print returns the number 1 always after completion of execution, echo does not. And on this they often like to build puzzles of such a plan in order to move their brains:

And a typical problem:

And then you ask, is this used somewhere? The answer is NO, this is considered insanity, and if it were my will, I would make print only a synonym for echo. Despite the fact that no one ever uses this possibility, this possibility still remains as entertainment for theorists.

Which quotes are correct to use to output text in PHP

I will not load your head with insanity, so I told one thing above. Therefore, let's immediately move on to how to draw a conclusion correctly!

Rule number 1 - without quotes, we write numbers and variables:

Rule number 2: We use single quotes when we want to print unchanged what is contained inside the quotes, and we always want to do this:
Mr. propper";

Note that the tags are sent to the browser unchanged, and the browser, in turn, processes them and displays them as tags, that is, already formatted code. Again, we reiterate that PHP is generating HTML, not text.

The exception to the rule is when we want to output special characters such as a greater than or less than sign, or an entire block of HTML, we use the htmlspecialchars function:
Mr. propper");

Rule number 3: we use double quotes when we want to display the processed string, that is, almost never. Despite the fact that the following code will be able to print a variable:

This code is considered terrible, trite because we cannot read our code and do not understand its behavior:
Looking at the code above, would Friends or FrienBeer be output? This is called non-obvious behavior, which means that the behavior of this code can be changed more than once in the future. Never write code in a way that you can't immediately understand with a quick glance. It would be correct:

But despite this, we use double quotes in two cases when we need to display a line break (not HTML) or a special character:
In the source code of the page, you can see how the newline \r\n works and understand the difference.

Embedding output from PHP into HTML

PHP is just a tool, a way to insert some generated piece of data into HTML, so we always use PHP inside HTML. Simple option:

The above syntax is multi-faceted, inside the PHP construct we can not only use echo, but also any other operations including creating variables, etc. etc. But if you ONLY need to output a variable or text in one action (only one echo), you can use the shorthand syntax:
"; $y = "b"; ?>

The most interesting thing is to use combined syntax for PHP and HTML:

As you can see, inside the iteration of the loop, you can display pure HTML, just close PHP construct and continue to output HTML. This method is much better than the usual echo in that our PHPStorm IDE code editor will highlight the syntax of the code and simplify the development of the site.

The article will be updated and improved. But even now I have outlined in it all the basic methods for outputting text and variables in PHP

The note: the adaptive version of the site is activated, which automatically adjusts to the small size of your browser and hides some details of the site for ease of reading. Happy viewing!

Hello dear readers, and soon PHP developers;) Today's blog post site on! is devoted PHP basics: syntax features, data output, variables, and error handling. In the course of the PHP lesson cycle, I will try to tell you as many interesting and useful things as possible, while trying not to stretch the articles.

PHP blocks

The first thing you should know is that PHP code must always be wrapped in PHP tags:

You can also use:

First, each instruction (expression) must end with a semicolon; For example:

// tell PHP to show us absolutely all errors related to it header("Content-Type: text/html; charset=utf-8"); // encoding echo "Our first PHP script works!
"; // display text on the page ?>

Second, all the same can be written in one line, between instructions in one line you can put as many spaces as you like, including no spaces at all:

"; ?>

Third, PHP instruction can be broken into multiple lines:

"; ?>

Result:

We observe that the browser interpreted each newline as a normal space, which is to be expected.

fourth, in PHP, as in all programming languages, there are comments. There are 2 types in PHP: single-line and multi-line.

// - single line comment # - also a single line comment /* Your comment */- multiline comment

There is an opinion that for a good programmer, comments should make up 30% of all code. However, the redundancy of comments is also completely useless, you should not leave comments like “here I looked out the window and scratched my nose.”

Data output in PHP

Data output in language PHP programming carried out by means of two main language constructs:

"; print "This is exactly the same text"; ?>

The difference is that in execution print returns one, and echo returns nothing. If you don't know how exactly to use it, then use echo and do not bother, especially when using echo, you can do this:

", "Our first PHP script works!", "";
//also, but with a print: print"

"; print "Our first PHP script works!"; print "

"; ?>

So besides the fact that the echo itself is shorter than the print by 1 character, it also allows you to write down the output constructions more briefly. Each comma in the example above simulates a new echo call. In other words, we called the echo three times, instead of each time writing: echo echo echo, as we did in the case of the print.

By the way, the same thing could be written like this:

This is what I meant in the previous article when I mentioned that .

Variables in any programming language are used to store any information within themselves, that is, a variable is our vessel. We can first put one there, then remove the first put the second, or we can leave the first and report the second (and the third, etc.).

Variables in PHP begin very symbolically - with a dollar sign $, after which WITHOUT a space there must be either a Latin letter or an underscore (a number cannot be the first character in a variable name). Further, the variable name can contain both Latin letters and numbers, and still the same underscore character. For example:

$name="Sergey"; $_blog1="Site on!";
echo $name, " - blog author ", $_blog1; ?>

Result:

Variable names are case sensitive! That is, $Name, $naMe, $name are three completely different variables. If we want to put something new into an already existing variable, then the old value of this variable will be automatically erased:

$name="Sergey"; $_blog1="Site on!"; $name="Andrey"; //write new value to name variable
echo $name, " - blog author ", $_blog1; ?>

Result:

Naturally, we can pass the value of one variable to another:

$name = "Sergey"; $_blog1 = "Site on!"; $name = $_blog1;
echo $name, " - blog author ", $_blog1; ?>

Result:

At the same time, the value of the $_blog1 variable remained in it.

Unlike strings, when entering a number into a variable, quotes are not needed:

$name = 45;

As with putting a variable into a variable:

$name = $_blog1;

After the end of the code on the page, everything PHP variables are automatically deleted. But there are rare cases where we need to forcefully delete a variable before the code ends. For this, the function unset:

$name="Sergey"; $_blog1="Site on!"; $name=$_blog1; unset($name); //remove variable name
echo $name, " - blog author ", $_blog1; ?>

Result:

Dealing with Errors in PHP

So we smoothly moved on to the topic of errors in PHP. As you can see, we are accessing a variable $name, which was ruthlessly removed before - this led to the notice (Notice). Notice should be considered a real error, although in most cases it is absolutely harmless.

PHP even tries to tell us where and what kind of mistake we made. In our case, he writes:

Undefined variable: name

Which translates as "undefined variable: name" and then shows us the file and the line on which this whole incident happened:

In Z:\home\localhost\www\blog2\second-page.php on line 10

That is, in the file second-page.php on the line 10. In this case, PHP guessed right, but it often happens that the error is one or more lines higher, for example, when we forget to put a semicolon at the end of the next statement:

$name="Sergey"; $_blog1="Site on!" //oops, forgot :(
echo $name, " - blog author ", $_blog1; ?>

Result:

In this case, we have the so-called parse error, which prohibits the execution of all scripts on the page, and therefore, apart from the error, it showed nothing to us and will not show it until we fix it. Considering the consequences, this is a serious mistake, which, unlike the previous one, must be corrected! But there is nothing to fear here.

PHP tells us that the error is on the eighth line (on line 8), however, in fact, I forgot to put a semicolon 2 lines above:

I draw your attention to the fact that when you see "syntax error, unexpected", then in 99% of cases it means that you forgot to put a semicolon.

The next thing you need to remember for yourself is that you need to correct (fix) errors from top to bottom! Since one mistake can often lead to a dozen others, therefore, having corrected the very first one, there is a fairly high chance that all the others will automatically disappear.

There are two more types of errors that every PHP developer should be aware of - these are FATAL error and Warning, which also must be fixed! However, both of these errors do NOT terminate other PHP scripts on the page, unlike the Parse error.

When developing online stores, websites, or any scripts, it is impossible to do without variables.

During the execution of the script, the data needs to be stored somewhere, for this there are variables. Variables can store any data (numbers, strings) and there is no type binding.

variables in php start with the $ sign, and can consist of Latin letters, numbers, and underscores.

Writing and outputting variables

Let's write a small script to work with variables:

In addition to writing and outputting variables on the screen, we can perform mathematical operations with them:

A number will appear on the screen. 15 . When displaying a variable on the screen, we used double quotes ("). If you use single quotes ("), then the variable name will not be displayed on the screen, but the name of the variable. For example:

On the screen we will see Answer: 15, a " Answer: $result».

Working with variables one of the most necessary things in programming in any language. It is not possible to write a script without using variables. Take a closer look at them.

When developing online stores, websites, or any scripts, it is impossible to do without variables. During the execution of the script, the data needs to be stored somewhere, for this there are variables. Variables can store any data (numbers, strings) and there is no type binding.

OX2 2014-10-02 2014-10-02
A computer