Operations with PHP changes (operators). Number crunching and mathematical operations in Php are complete

Golovna / Corisna information

Programs that need to produce advanced numerical, scientific or statistical calculations are unlikely to see my Internet scenario as an attractive candidate for this role. However, despite all that has been said, PHP offers a wonderful set of functions that will cover most of the mathematical tasks that arise in the process of creating scripts for the Internet. In addition, PHP language provides several advanced capabilities, such as high-precision number arithmetic, as well as features of hashing libraries and cryptographic libraries.

Developers of the PHP language have adopted a completely priming approach and have not made frequent tests to re-run the wheels designated for the designated mark. On the right, there are a lot of fundamental mathematical functions that are found in PHP, and simply wrappers around analogues of these functions in C.

Mathematical operations

Most of the mathematical operations in our PHP occur in the form of functions, rather than in the form of operations. In addition to the updating operation, PHP uses five operations to perform simple arithmetic operations, as well as shortcut operations that allow you to add shorter incremental and decremental expressions, as well as assignments.

Arithmetic operations

The five basic arithmetic operations include those operations that are implemented in any multifunctional calculator, as well as the operation submodulo (%). A short description of arithmetic operations is given in the table:

Arithmetic operations
Operation Description
+ Rotates the sum of the values ​​of two of its operands
- Since there are two operands, the value of the right operand is subsumed by the value of the left one. If there is no right-hand operand, the operation rotates the value of the operand with the reverse sign
* Rotates the value of two of its operands
/ Rotates the floating point result of the value of the left operand by the value of the right operand
% Rotates the surplus of the entire value of the left operand by the absolute value of the right operand

When the first three described arithmetic operations (+,-,*) are deleted from the program, the trace is added, so that when these operations are deleted, an expanded type of floating point value with increased precision is generated or more numbers. This is important to note: if the operand of the operation is an integer number, then the result is an integer number, and if you want one of the operands to be a floating point number with double precision, then the result is a floating point number high precision. The same type of extension is available during the final operation of the subsection; In addition, there is such an additional effect that the result becomes a floating point number of increased precision, since the division does not work without excess (totally).

The modulo (%) operation in the PHP language accepts integer operands, and this operation is limited to floating-point numbers of lower precision, and the digits are first converted to the whole number (using the given shot part). The result of such an operation is an integer number.

Increment and decrement operations

It is important that the syntax of PHP language is simplified from that of C language, and C programs are famous for their love for writing and are written in C language. The increment and decrement operations, taken from the C language, allow you to more briefly represent expressions like $count = $count + 1, which are often used in programs.

The increment operation (++) is used to add one to the value of the change, which expands the operation, and the decrement operation (--) adds one to the value of the change.

The skin of these two operations has two varieties - suffixnu(in this form the sign of the operation is located directly behind the change, as the operation expands) and prefix(In this form, the sign of the operation is placed directly in front of the change, as the operation is expanded). Both different types may have the same side effect, when changing the value of the change, and suffix and prefix operations rotate different values ​​when vicoristic as a result. The suffix operation works in such a way that the changeable value is changed after the value is rotated, and the prefix operation works in such a way that the value is initially changed, and then the changeable one is rotated again significance. The indicated importance can be identified by using the decrement and increment operations assigned to operators:

PHP code $count = 0; $result = $count++; echo "Result of $count++ increment: ".$result."
"; $count = 0; $result = ++$count; echo "Result of ++$count increment: ".$result."
";

The following operators form the next icon in the browser window:

Increment operations

In this application, the operator $result = $count++ is completely equivalent to the operators:

PHP code $result = $count; $count = $count + 1;

The order of the operator $result = ++$count is equivalent to the following operators:

PHP code $count = $count +1; $result = $count;

Operations assigned

Increment (and decrement) operations allow you to change the code required to add one to the value of the change, but do not allow the speed of the code in which the change is given the result of adding a value to another number or the result of the calculation of other arithmetic operations. Fortunately, all five arithmetic operations can be assigned to similar operations (+=, -=, *=, /= and %=), which allows you to assign a change in one short expression to the result of an arithmetic operation above the value of the change. For example, operator

PHP code $count = $count * 3;

can we shorten the introductions like this

PHP code $count *= 3;

Simple mathematical functions

The next stage of program compilation, in line with the fact that arithmetic operations will stagnate, applies to a number of different functions. Functions allow you to solve problems such as converting from one numeric type to another (div. article “Data types”) and searching for the minimum and maximum number of a set of numbers. The following table shows simple mathematical functions:

Simple PHP math functions
Function Description
floor() Takes a single actual parameter (usually a variable precision floating point number) and rotates the largest integer number that is smaller or older than the actual parameter (rounded down)
ceil() These functions are shortened for the word ceiling. The function takes a single actual parameter (usually a floating-point number of high precision) and rotates the smallest integer number that is larger or lower than the actual parameter (rounded up)
round() Takes a single actual parameter (value is a floating point number of variable precision) and rotates the nearest integer number
abs() The absolute value of a number. If the numeric actual parameter has a negative value, the function rotates the positive number; If the actual parameter is positive, the function rotates the actual parameter itself
min() It accepts as many numeric actual parameters (or at least one) and rotates the least of all the values ​​of the actual parameters
max() It accepts as many numeric actual parameters (or at least one) and rotates the largest value of the actual parameters

For example, the result of the skin virus is older than 3, the remaining value of the skin virus with the click of the function is also older than 3:

PHP code $result = min(3, abs(-3), max(round(2.7), ceil(2.3), floor(3.9))));

Viroblennya of vipadkovyh numbers

In PHP, there are two random number generators (click here for the additional function rand()і mt_rand()). Three functions of the same importance are associated with the skin of these generators: the function of setting the cob value ( srand()і mt_srand()), the function itself is a function that selects the largest integer that can be rotated by the generator (( getrandmax()і mt_getrandmax())). The getrandmax() and mt_getrandmax() functions rotate the values ​​of the largest number that can be rotated by rand() or mt_rand(), on Windows platforms this value is enclosed by the value 32768.

The choice of a specific function for generating pseudo-variable numbers, such as the function rand(), can be found in which libraries are used to compile the PHP interpreter. In addition, in the mt_rand() generator, the very function of generating pseudo-variable numbers (mt - short for Mersenne Twister) is always used, and the author of the operational documentation for the mt_rand() function confirms that this function It also has more speed and more speed (from the point of view of cryptography), no rand ().

When using different versions of PHP for different platforms, it appears that the functions rand() and mt_rand() generate seemingly quite pleasant numbers, without first specifying the original value. You shouldn’t trust such an enemy. First of all, programs that have the function of generating random numbers without specifying a cob value are very easy to transfer to other platforms, and, in other words, the reliable operation of assigned functions without specifying a cob value is guaranteed.

A typical method for specifying a cob value for any of PHP's cob number generators (using the mt_srand() or srand() functions) is as follows:

PHP code mt_srand((double)microtime()*1000000);

This operator specifies the clock value of the generator, equal to the number of microseconds that pass until the hour from the remaining whole second. (Casting this operator to type double is not necessary because the microtime() function rotates a row that is treated as a whole number in the multiplication operation, and not in the operation of passing parameters to the function.) Recommended reading and enter the operator for specifying the cob value, specifying I don’t quite understand the importance of this operator; You can simply place this operator on the skin side of PHP, just once, before the subordinate functions mt_rand() or rand(), and this operator will ensure that the correct point changes and will immediately change no random sequence.

This specific method of obtaining the cob value was deeply thought out by these fakhivtsy, which will completely understand all the nuances of the generation of pseudo-capacity numbers, so that, for all that, we will once again be deprived of the best results from any attempts of any kind of programmer. at least it's "tricky".

Obviously, the pseudo-integer number rotation function is designed to rotate only integer numbers, and a random integer number from a given range can be easily converted to a similar number with a floating point (say, a number from a range to ID 0.0 to 1.0 inclusive) for additional virus on rand() / getrandmax(). After these instructions, the range can be scaled and destroyed as necessary. Butt pointed lower:

PHP code // Let's say we need to generate a random number from 100.0 to 120.0 $random = 100.0 + 20.0 * mt_rand() / mt_getrandmax(); echo $random."
// Generate whole numbers (100 - 120); echo round($random);

Try updating the page with this code a few times to get started with generating random numbers.

Mathematical constants

PHP version 4.0 had only one mathematical constant, described in the documentation - M_PI (the value of the number π, represented as a floating point number of equal precision). And starting with version PHP 4.0.2, a lot of new constants were introduced. Most of these new constants were up to π (or up to multiples of its value), e (or up to multiples of its value), and also up to the square root; In addition, these constants existed before other types. In recent releases, for a number of reasons, the list of constants has once again been reduced to an evenly small number of specified mathematical constants:

PHP Mathematical Constants
Constant Description
M_PI π
M_PI_2 π/2
M_PI_4 π/4
M_1_PI 1/π
M_2_PI 2/π
M_2_SQRTPI 2 / sqrt(π)
M_E e
M_SQRT2 sqrt(2)
M_SQRT1_2 1 / sqrt(2)
M_LOG2E log2(e)
M_LOG10E log(e)
M_LN2 loge(2)
M_LN10 loge(10)

Checking the number format

The PHP language has a small function that allows you to check the correctness of the representation of numbers. Regardless of the fact that there is extensive type control in PHP every day, it is recommended, when necessary, to carry out these checks on the code so that you can predict the characteristics of the extracted results, and also choose the shortest method Ib their preparations.

The first and simplest verification applies to the vicoristic function is_numeric(). As with most other such transformations, the is_numeric function returns the Boolean result - true, when passing its parameter a numeric data of any type (signed or unsigned, integer or floating point) Because it is mathematically different, because it rotates the permissible numerical values .

For additional functions is_int()і is_float You can calculate the number of goals and shotguns. Two more reversals and three folding ones: functions is_finite()і is_infinite() Allow the very same reversals to indicate their names (and the number at the end or at the end). However, strictly speaking, the range of values ​​on which these functions are expanded cannot include actual inconsistencies (and which can be verified in other words, what number may have an infinitely large value?). It is necessary to select between the range of floating point values ​​allowed in a particular system.

Below is the butt of the vikor of these functions:

PHP code is_numeric(4); // true is_numeric(25 - 6); // true is_numeric("25"); // true is_numeric("25 - 6"); // false is_int(4); // true is_int(4.2); // false is_int("4"); // false - the verification of the suvorich is given, the lower verification for the additional function is_numeric() is_float(4); // false is_float(4.0); // true is_float(M_PI); // true

Redesign of numerical systems

For the purpose of direct and reverse conversion of numerical values ​​from the external statement, the basis of the number system 10 is established in the internal one. In addition, you can tell the PHP interpreter that the current statement The highest numbers specified on stand 8 are used (for which you must enter before the number wire 0), or hexadecimal numbers specified on base 16 (for which you must enter the prefix 0x before the number).

Incredibly, after reversing the numbers from the external data, the internal data is stored in memory in a double format, and all the main arithmetic and mathematical calculations are carried out in the operating system itself substitues 2. In addition, the PHP language has a number of functions for converting numbers into one the basics of the calculation system before the other. Additional information about these guidance functions is in the table below:

Functions of re-creation of numerical systems
Function Description
BinDec() Takes a single serial parameter, which is a double integer number (the number on base 2), and rotates the serial representation of this number based on the number system 10
DecBin() Similar to BinDec(), except it transforms the number system from 10 into a base number system of 2
OctDec() Similar to BinDec(), except it transforms the base number system 8 into the base number system 10
DecOct() Similar to BinDec(), except it transforms the base number system 10 into the base number system 8
HexDec() Similar to BinDec(), except it transforms the base number 16 into the base number system 10
DecHex() Similar to BinDec(), except it converts the number system from 10 to the base number system of 16
base_convert() Accepts a row parameter (which represents an integer number that facilitates transformation) and two integer parameters (output and base). Rotate the row to recreate the number. In this row, the numbers higher than 9 (from 10 to 35) are represented by the symbols a-z. I'm off, and I'm putting the blame in between 2-36

All functions for converting number systems are functions of special purpose, such as converting numbers from one specific base to another. The culprit is the base_convert() function, which accepts additional parameters from the values ​​of the initial and resulting bases.

Please note that all functions for converting numerical systems accept row parameters and rotate string values, or you can convert tens numeric parameters and rely on the correct conversion of the PHP interpreter. In other words, the option to use DecBin("1234") and DecBin(1234) to produce the same result.

Exponential and logarithmic

The PHP language includes standard exponential and logarithmic functions of two types - for working in base 10 and base 10 (as shown in the table).

In PHP, the exp() function has been transferred to return the number e from the step indications, as well as a daily function with one parameter, which can be used to return the number 10 to the step indications. However, the replacement of this function can be used and the pow() function with two parameters, setting 10 as the first parameter.

You can find out that exponential and logarithmic functions with this very substitution have a one-to-one return by checking the identity of the results as follows:

PHP code $test_449 = 449.0; $test_449 = pow(10, exp(log(log10($test_449))))); echo "test_449 = $test_449"; // test_449 = 449

Trigonometric functions

Our PHP translations have a standard set of basic trigonometric functions, additional information about what is shown in the table:

Trigonometric functions
Function Description
pi() Does not accept parameters and rotates closer to the value of the number π (3.1415926535898). Can be used interchangeably with the M_PI constant
sin() Accepts a numeric parameter in radians and rotates the sine of the parameter in the form of a floating point number of increased precision
cos() Accepts a numeric parameter in radians and rotates the cosine of the parameter in the form of a floating point number with increased precision
tan() Accepts a numeric parameter in radians and rotates the tangent of the parameter in the form of a floating point number of variable precision
asin() Accepts a numeric parameter and rotates the arcsine of the parameter in radians. The input data must be in the range -1 to 1 (the function of rejecting input data that falls outside this range will result in rejecting NAN). The results vary in the range from -π/2 to π/2
acos() Accepts a numeric parameter and rotates the arc cosine of the parameter in radians. The input data must be in the range -1 to 1 (the function of removing the input data that falls outside this range is to remove NAN. The results are in the range from 0 to π
atan() Accepts a numeric parameter and rotates the arctangent of the parameter in radians. The results vary in the range from -π/2 to π/2

Below is an example of a folded table for calculating trigonometric functions for “standard” functions:

PHP code function display_trigonometry($func_array, $input_array) ( // Function header echo " ";) echo "// Enter table data foreach($input_array as $input) ( echo " "; foreach($func_array as $func) ( echo " ";) echo "";) echo "
Value/function$func
".sprintf("%.4f",$input).""; printf("%4.4f", $func($input)); echo "
"; ) display_trigonometry(array("sin", "cos", "tan"), array(0, M_PI/6, M_PI/3, M_PI/2, M_PI));

The butt of using trigonometric functions in PHP

The removal of even large (or not insignificant) values ​​of the tangent is due to the fact that theoretically the signs are equal to zero, but in reality the fractions subdivide from zero due to rounding.

Calculation with sufficient accuracy (using BC functions)

Integer types and floating-point types with variable precision are suitable for most mathematical problems that arise in online scenarios for the Internet, as well as for saving skin data. and the value represented by these types is transferred to the computer memory, so that The dimensions and accuracy of the representation of numbers of these types inevitably impose limitations.

Insanely, the exact ranges of values ​​of these types can lie in the architecture of the server computer, and the values ​​of integer numbers can range from -2 31 -1 to 2 31 -1, and numbers with floating point have a lower precision and can represent numbers with approximate accuracy There are 13 to 14 tenth digits. On the other hand, for a higher task, which results in a wider range of data and greater accuracy, in our PHP transfer mathematical functions with reasonable accuracy(also called BC functions - in the name of a calculation utility with considerable accuracy, based on the features of the Unix system).

It may turn out that functions of sufficient accuracy are not included in the compilation of the PHP interpreter, especially if the user carries out such compilation independently, for which the user is obliged to know that at the stage The configuration bath must be enabled before the parameters are stored. --enable-bcmath. To check who has access to the assigned functions, try calculating the expression bcadd("1","1"). If the message about the error is removed, which involves an unspecified function, you will need to reconfigure the configuration and recompile the PHP interpreter.

In functions BC, as parameters and values, which are rotated, it is not numeric types with given fixed values, but rows that are rotated. The fragments in the PHP language of the dovzhin rows are limited by the amount of available memory, the numbers that appear in the layouts can result in a dowzhin. The main calculations are taking place in tens of years, and there is a lot of guessing about how people can get away with the help of a sheep and a paper (as people can stock up on terpenes as quickly as possible). BC functions that operate with integer numbers operate accurately and allow you to calculate as many digits as necessary, and in functions that operate with numbers with a point that floats, calculations are calculated exactly to the specified value. Only tens of discharges. Additional information about the functions of BC can be found in the table below:

Mathematical functions with sufficient accuracy (BC functions)
Function Description
bcadd() Accepts two series parameters that represent numbers, and a necessary integer parameter representing the scale multiplier values. Rotates the sum of the first two parameters in the row view, with a number of tenth positions in the result, which is indicated by the parameter with the values ​​of the scale multiplier. Since the parameter is based on the values ​​of the scale multiplier and not the tasks, the tasks are replaced by the scale multiplier
bcsub() Similar to bcadd(), except that it rotates the result of another parameter from the first
bcmui() Similar to bcadd(), except that it rotates the result of multiplying its parameters
bcdiv() Similar to bcadd(), except that it rotates the result of the first parameter to another
bcmod() Rotates the module (surplus) from the subsection of the first parameter to another. The fragments of the value that is rotated are converted to a whole type; the function does not accept a parameter with the values ​​of the scale multiplier
bcpow() Add the first parameter to the steps, indicating another parameter. The number of tenth positions in the result is indicated by the scale multiplier, as in the tasks
bcsqrt() Rotates the square root of a parameter in a number of tenths positions, which corresponds to the values ​​of the non-binding scale multiplier
bcscale() Sets the scaling factor for the next clicks of the BC function

Most of these functions take the remaining parameter as a non-binding scaling factor (integer number), which means how many tenths of a position are included in the result. Since such a parameter is not a task, then the scale multiplier is used to determine the scale multiplier, which, in its turn, can be installed using the bcscale() function. The value specified for this value (the value that is determined if the script does not stall the call to the bcscale() function) can also be specified in the php.ini initialization file.

Below is an example of a vicor function with sufficient accuracy for precise calculation of entire arithmetic operations. Vikonanny offensive code:

PHP code for ($x = 1; $x< 25; $x++) { echo "$x$x= ".bcpow($x, $x)."
"; }
More precisely, the calculation of astronomical quantities using the additional function BC

If for these calculations using the PHP integer type, then the revaluation of the integer would take place long before the end of calculation, so in the other part of the expansion cycle they worked out the method of taking the nearest number with a floating point.

Masivi Processing forms 1 2 3 4 5 6 7 8 9 10

Logical operations are present in all programming languages. PHP no blame. In addition to the simple subject, multiplication, addition and obviousness emerges in a completely numerical and excessive subject, which we will now talk about, and also analyze them, vikoryst and report butts.

Integral hem means displaying a whole part as a hem. For example, if we divide 5 by 2, then we subtract 2, not 2.5.

With too much division, everything is different. There is a surplus in the bottom for the whole number. For example, by dividing the same five, you subtract not 2, but 1, therefore, dividing 5 by 2, we subtract 2, and add 1 to the surplus.

How to conquer a whole subfield in PHP

For example, in Python this subfield is defined using a simple operator: "//".

And in PHP It will not be so easy to earn money, but still the process does not allow you to learn more about your language.

Let's point out the butt, how it can be implemented.

U PHP In the seventh version, the function looks like this:

Intdiv();

In the older version, this function looks like this:

The same method works for all versions:

Floor();

How to arrange it?

For example, let’s take the first function and decide to end up in approximately the same way.

$result = intdiv(10, 3); echo $result;

PHP is too weak

In order to remove the entire surplus from the floor to PHP Just add the "%" operator.

$i = 10% 3; echo $i;

Like Bachimo, everything just doesn’t require a trivial explanation.

Where can you stagnate?

Knowledge of the whole field in PHP They will be even more colorful if you need to reverse two numbers, create an inverted number (popular to the right), or, for example, a program called FizzBuzz. The point is that you can write a cycle from 1 to 100, which divides each number by 3 and 5. If the number divided by 3 gives 0, then we write Fizz, if it is divided by 5, then Buzz, and if , Having divided і 5, і 3, we subtract 0 from the surplus, then we write FizzBuzz. This is even more popular on the internet. Since you wrote it yourself, you can write about yourself.

Or, for example, we can use the number 452 to print all the numbers (4, 5, 2).

Visnovok

Insanely, the whole and redundant part of the cinnamon and shriveled fruits come out often, and it’s not as easy to pick them out as in Python, but still important.

Now you're on the croq closer to the vivchennya movie program PHP and in the future you will become even closer, as you so diligently overcome difficulties.

Operations with PHP changes (operators)

For this purpose, use different groups.

An operator is something that is made up of one or more values ​​(viraziv, as they say in programming jargon), which can be calculated as a new value (the whole structure can therefore be considered as a viraz). The result shows that functions or other structures that rotate values ​​(for example, print()) by operators who are responsible for solving physical structures (for example, echo()), as they don’t turn anything.

Arithmetic operations in PHP

Do you remember the school arithmetic ambushes? Move lower operators do the same thing.

The operation under ("/") always rotates the speech type, meaning that the values ​​are whole (or rows that are converted to whole numbers). Otherwise, the result will be different.

The operation of calculating the surplus in the division " % It works only with whole numbers, so condensing it to fractions can lead to the wrong result.

Mozhlive vikoristannya arches. The priority of some mathematical operations over others and the change of priorities when vicoristan arches in arithmetic expressions correspond to basic mathematical rules.

Increment and decrement operations

PHP, like C, supports prefix and postfix increment and decrement operators.

Postfix operators for increment and decrement

As in the language, these operators increase or change the values ​​of the variable, and in the language, rotate the values ​​of the variable $a before change. For example:

$a=10;
$b=$a++;
echo "a=$a, b=$b"; // Enter a = 11, b = 10

As you say, the fresh corn $b got the value of the change $a, And then the rest was incremented. Therefore, it turns out that the value of which is assigned a variable $b, it may be more complex - at any time, increment $a There will be more after this calculation.

Prefix operators for increment and decrement

There are also increment and decrement operators that are indicated, and not after the name of the change. Obviously, rotate the value of the change after the change. Butt:

$a=10;
$b=--$a;
echo "a=$a, b=$b"; // Print a = 9, b = 9

Increment and decrement operations often stagnate in practice. For example, the smells are noticeable almost in any cycle for .

echo "

Postfix increment

" ;
$a = 5;
echo "Main boot 5: " . $a++. "
\n" ;

\n" ;

Echo "

Prefix increment

" ;
$a = 5;
echo "Main boot 6: " . ++$a. "
\n" ;
echo "Main boot 6: " . $a . "
\n" ;

Echo "

Postfix decrement

" ;
$a = 5;
echo "Main boot 5: " . $a - . "
\n" ;

\n" ;

Echo "

Prefix decrement

" ;
$a = 5;
echo "Main boot 4: " . - $a. "
\n" ;
echo "Main boot 4: " . $a . "
\n" ;
?>

String operations

PHP has two operators for working in rows. The first is the concatenation operator ("."), which rotates the combination of the left and right arguments. The other is the assignment operator with concatenation, which adds the right argument to the left one. Let's point a specific butt:

$a = "Hello";
$b = $a. "World!" ; // $b place the row "Hello World!"

$a = "Hello";
$a .= "World!" ; // $a place the row "Hello World!"
?>

Bitwise operations

These operations are intended for the operation (installation/removal/verification) of groups of battles for the entire change. The bits of a whole number are nothing more than the digits of that same number written in the two-digit number system. For example, in the double system, the number 12 looks like 1100, and 2 looks like 10, so it turns out 12|2 Give us the number 14 (1110 for the deuce notation). If the change is not whole, then it’s out
Initially it is rounded, and then before it stagnates with lower operators.

To represent one number, 32 bits are used:

  • 0000 0000 0000 0000 0000 0000 0000 0000 – value zero;
  • 0000 0000 0000 0000 0000 0000 0000 0001 – ce 1;
  • 0000 0000 0000 0000 0000 0000 0000 0010 – tse 2;
  • 0000 0000 0000 0000 0000 0000 0000 0011 – tse 3;
  • 0000 0000 0000 0000 0000 0000 0000 0100 – tse 4;
  • 0000 0000 0000 0000 0000 0000 0000 0101 – tse 5;
  • 0000 0000 0000 0000 0000 0000 0000 1111 - ce 15;

Bitwise operators:

butt Name Result
$a & $b Bitwise "i" The only bits that are installed are both $a and $b.
$a | $b Pobitov "or" The bits that are installed are either $a or $b.
$a^$b Viklyuchne or Only two bits are installed, as either only $a or only $b is installed
~$a Listed These bits are installed, both $a is not installed, and the other way around.
$a<< $b Destroyed left All bits of the exchangeable $a are placed on $b position to the left (the skin position is “multiplied by 2”)
$a >> $b Zsuv right-handed All bits of the exchangeable $a are placed on $b position to the right (the skin position may be considered “divided by 2”)

Leveling operations

Equalization operators, as their name suggests, allow you to equalize two values.

These are their own unique operations, so regardless of the types of their arguments, they always turn one of two: false or else true. Equalization operations allow you to equalize two values ​​between each other and, like a brain, rotate true, And there is no way - false.

PHP allows you to add scalar variables. It is not possible to rotate arrays of objects in PHP. They cannot be equalized (with the help of the == operator), unless such an operation is executed in PHP without any precedence. So we are surprised that two completely different massifs, when they are equal, need help == appear to be rapt, however, guess what before the exchange of offenses the operands are transformed into a word array, as soon as possible and equal.

Marvel at the details about the upgrading of massifs.

Operators:

butt Name Result
$a == $b Rivno TRUE because $a is related to $b.
$a === $b Same thing TRUE because $a is related to $b and is the same type. (Added in PHP 4)
$a != $b Doesn't compare TRUE because $a is not related to $b.
$a<>$b Doesn't compare TRUE because $a is not related to $b.
$a !== $b Not the same thing TRUE because $a is not the same as $b or because it smells of different types (Added in PHP 4)
$a< $b Mensche TRUE if $a is strictly less than $b.
$a > $b More TRUE if $a is strictly more than $b.
$a<= $b Less or more ancient TRUE because $a is less or more important than $b.
$a >= $b More or more ancient TRUE because $a is larger or more expensive than $b.

Logical operations

Logical operators are used inclusively for work with logical arguments and also rotation false or else true.

Let's create a table of PHP logical operators:

It is important to note that the calculation of logical expressions, which is why such operators always go to the right, whereby the result is already obvious (for example, false&&is always gives false), then the calculations are cut off, as if the virus has a function. For example, in the operator $logic = 0&&(time()>100); standard function time() will not be called at all.

Be careful with logical operations - do not forget about winning the symbol. To restore respect, for example, | і || - two completely different operators, one of which can potentially rotate any number, and the other - only falseі true.

The increment (++) and decrement (--) operators do not work with logical variables.

Equivalence operators

PHP, starting from PHP4, has the same equalization operator - a triple sign of equality === ,
or the reversal operator on. PHP can tolerate being set to the point where the rows are implicitly converted into numbers, and just like that.
For example, the offensive code shows that the meanings of the changes become more significant:

$a=10;
$b = "10";

And they don’t care about those who are mean $aє number, and $b- Row. Now let's look at another butt:

$a=0; // Null
$b=""; // empty stitch
if($a==$b) echo "a and b regions"; // Print "a and b regions"

I want $aі $b Obviously, they are not eager to tell the most common sense of this word, the script declares that the stink is being avoided. Why are you so excited? On the right is that while one of the operands of a logical operator can be treated as a number, two operands can be treated as a number. In this case, the empty row is transformed into 0 which then equals zero. It's not surprising that the operator echo ask.
The problem is dominated by the equivalence operator === (Threefold jealousy). It just equals the two definitions, or their types. Let's rewrite our example from this operator's website.

PHP has all the basic mathematical operations available. As operands can be used as targets, so can speech numbers.

The table contains a list of arithmetic operators:
OperatorSignDescription
Dodavannya + Add two values
Vіdnіmannya - Taking one meaning from another
multiplication * Multiply two values
Podil / Divide one value into another
Remove the excess from the bottom % The division of one value onto another and the reversed surplus (divided by modulus)
Increment ++ Shortening a number by one
Decrement -- Shortcut recording of changing a number by one
Unarne zaperechernya - Converting a positive number into a negative one or a negative number into a positive one

Operators subdivision, multiplication, subsection, subsection by module and addition

The operators simultaneous, multiplying, subdivision, submodulo and addition are explained in the same way as in mathematics. Here it is important to give respect to the operators of both modulo and submodulo operators.

The sub operator ("/") rotates a number with a floating point, except for the rows that contain whole numbers (or rows that turn into whole numbers), which are divided into whole numbers - in whose row the whole value is rotated.

result2 = $result2
"; echo "result3 = $result3
result4 = $result4"; ?>

When dividing by modulo, the operands are converted into whole numbers (with the fractional parts removed) into the beginning of the operation. The result of the operation is the same as the division:

Unarne zaperechernya

The unary enumeration operator is indicated by a "-" sign and changes the value of its single operand on the enumeration:

In this case, round arms are not needed because unary locks have the highest priority, but they help organize the code in such a way that it is clear that there is a place for adding numbers -5 and 4.

Increment

The increment operator is indicated by the sign ++ and can be expanded on either side of the operand it operates on. The value increases by one, just like adding one to the value. The actual result depends on whether the operator was stagnated before or after the operand with which it was stagnated. This operator is often substituted for changes, and it is often found in the middle of loops (loops will be discussed later).

Prefix form for increment

Prefix form- if the increment operator is incremented before the operand, this form of notation means that the increment will be incremented first: the value of the operand is increased by one and only then the instruction is incremented:

Postfix form for increment

Postfix form a few times are written differently - the increment is expanded every time after the operand. In postfix form, writing the first variable operand rotates the second value until the last value is increased by one:

Decrement

The decrement operator is denoted by the sign - , and when replacing the increment operator, it changes, and sometimes does not increase, the value of its operand by one. Decrement also allows prefix and postfix notation:

Logical operations are present in all programming languages, and PHP is not to blame. In addition to the simple subject, multiplication, addition and obviousness emerges in a completely numerical and excessive subject, which we will now talk about, and also analyze them, vikoryst and report butts.

Integral hem means displaying a whole part as a hem. For example, if we divide 5 by 2, then we subtract 2, not 2.5.

With too much division, everything is different. There is a surplus in the bottom for the whole number. For example, by dividing the same five, you subtract not 2, but 1, therefore, dividing 5 by 2, we subtract 2, and add 1 to the surplus.

How to conquer a whole subfield in PHP

For example, in Python this subfield is defined using a simple operator: "//".

But in PHP, earning money will not be so easy, but still the process does not support language knowledge.

Let's point out the butt, how it can be implemented.

In this version of PHP, the function looks like this:

In the older version, this function looks like this:

The same method works for all versions:

How to arrange it?

For example, let’s take the first function and decide to end up in approximately the same way.

$result = intdiv(10, 3); echo $result;

PHP is too weak

In order to display the entire surplus as a subfield in PHP, simply add the “%” operator.

$i = 10% 3; echo $i;

Like Bachimo, everything just doesn’t require a trivial explanation.

Where can you stagnate?

Knowing a whole subfield in PHP will be very useful if you need to reverse two numbers, create a number inversion (popular right), or, for example, a program called FizzBuzz. The point is that you can write a cycle from 1 to 100, which divides the given number by 3 and 5. If the number divided by 3 gives a surplus of 0, then we write Fizz, if it is divided by 5, then Buzz, and if , Having divided і 5, і 3, we subtract 0 from the surplus, then we write FizzBuzz. This is even more popular on the internet. Since you wrote it yourself, you can write about yourself.

Or, for example, we can use the number 452 to print all the numbers (4, 5, 2).

Visnovok

Insanely, the whole and redundant part of the cinnamon and shriveled fruits come out often, and it’s not as easy to pick them out as in Python, but still important.

Now you are one step closer to learning PHP programming, and in the future you will become even closer, as you try so hard to overcome difficulties.

© 2024 androidas.ru - All about Android