Chat in Telegram

Variables in PHP

08.09.2021 at 15:15
16
0

Hello everyone. Today we will talk about variables in PHP. Read about what it is and how to work with it below.

Let's start with the definition.
A variable is some value that corresponds to a specific name.
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, example:

$x = 2;

This operation is called variable assignment.

Of course, the result of an entire expression can also be assigned to a 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;

Note that PHP variable names are case sensitive. That is, $x and $X are two different variables.

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

$subscriberEmail = ‘user@email.com’;
$catName = ‘Snow’;
$dayOfWeek = ‘monday’;

Bad name example:

$result = $b ** 2 - 4 * $a * $c; // more appropriate name is $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, which is very important, since there are always several people working on large projects, and they always have to read each other's code. Again, 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, let's list these rules.

  • The variable name should consist only of English words, and even more so only of the letters of the English alphabet.
  • The name of a variable must start with a lowercase letter, and the next words contained in its name must start with a capital letter. This style is called lowerCamelCase.
  • No $catname, $cat_name or $CatName, just $catName.
loader
08.09.2021 at 15:15
16
0
Homework

The code should turn out in such a way that when the initial values of the variables change, it continues to work.

  • Set the variables $a and $b to 3 and 5, respectively. Use the third variable $c to change the values of these variables ($a will have 5, and $b will have 3)
  • Do the same, but without using the third variable, provided that only integers can be used as values
Comments
New comment