Php math operations. Operations on numbers in PHP


Programmers who need to perform sensitive numerical, scientific, or statistical calculations are unlikely to consider a web scripting language as an acceptable candidate for this role. But, despite the above, the PHP language offers an excellent set of functions that completely provide a solution to most mathematical problems that arise in the process of executing scripts for the web. In addition, PHP provides some more advanced capabilities, such as arbitrary precision arithmetic, hashing libraries, and cryptographic libraries.

The developers of the PHP language took a well-founded approach and did not make any attempt to reinvent the wheels designed for this purpose. The fact is that many of the most fundamental mathematical functions used in PHP language, are simply wrappers around the C counterparts of these functions.

Mathematical operations

Most mathematics in PHP is done in the form of built-in functions rather than operations. In addition to comparison operators, PHP offers five simple arithmetic operators, as well as some shortcut operators that allow you to construct shorter increment, decrement, and assignment expressions.

Arithmetic operations

The five basic arithmetic operations include those commonly implemented in any four-function calculator, plus modulo (%). Short description arithmetic operations are given in the table:

Arithmetic operations
Operation Description
+ Returns the sum of the values ​​of its two operands
- If there are two operands, then the value of the right operand is subtracted from the value of the left one. If there is only a right-hand operand, then the operation returns the value of that operand with the opposite sign
* Returns the product of the values ​​of its two operands
/ Returns the floating point result of dividing the value of the left operand by the value of the right operand
% Returns the remainder of an integer divided by the value of the left operand absolute value right operand

When using the first three arithmetic operations described above (+, -, *) in a program, you should take into account that when performing these operations, type propagation occurs from double-precision floating-point values ​​to integer values. What this means is that if both operands of an operation are integers, then the result is an integer, and if at least one of the operands is a double-precision floating-point number, then the result is a double-precision floating-point number. The same type propagation occurs when performing a division operation; in addition, there is an additional effect that the result becomes a double-precision floating-point number if the division is not carried out without a remainder (entirely).

The modulo (%) operation in PHP accepts integer operands, and when this operation is applied to double-precision floating-point numbers, then these numbers are first converted to integers (by discarding the fractional part). The result of such an operation is always an integer.

Increment and decrement operations

Much of PHP's syntax is derived from C, and C programmers are known for their love of brevity and take pride in it. The increment and decrement operators, taken from the C language, make it possible to more concisely represent expressions like $count = $count + 1, which are usually found quite often in programs.

The increment operator (++) is used to add one to the value of the variable affected by the operation, and the decrement operator (--) subtracts one from the value of the variable.

Each of these two operations has two varieties - suffix(in this form the operation sign is placed immediately after the variable affected by the operation) and prefix(in this form, the operation sign is placed immediately before the variable to which the operation applies). Both varieties have the same side effect of changing the value of a variable, but the suffix and prefix operations return different meanings when used as expressions. The suffix operation operates so that the value of the variable is changed after the value of the expression is returned, and the prefix operation operates so that the value is first changed and then the new value is returned to the variable. This difference can be detected by using the decrement and increment operators in assignment 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 statements produce the following output in the browser window:

Increment operations

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

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

Along with this, the operator $result = ++$count is equivalent to the following operators:

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

Assignment Operators

Increment (and decrement) operators reduce the amount of code required to add one to the value of a variable, but do not reduce the amount of code that assigns a variable the result of adding its value to another number or the result of other arithmetic operations. Fortunately, all five arithmetic operators have corresponding assignment operators (+=, -=, *=, /=, and %=), which allow you to assign the result of an arithmetic operation on the value of that variable to a variable in one short expression. For example, the operator

PHP code $count = $count * 3;

can be abbreviated as

PHP code $count *= 3;

Simple Math Functions

The next step in making a program more complex than one that uses only arithmetic operations is to use all kinds of functions. Functions allow you to perform tasks such as converting from one number type to another (see the Data Types article) and finding the minimum or maximum number in a set of numbers. The following table shows simple mathematical functions:

Simple PHP Math Functions
Function Description
floor() Takes a single actual parameter (typically a double-precision floating-point number) and returns the largest integer that is less than or equal to that actual parameter (round down)
ceil() The name of this function is an abbreviation of the word ceiling. The function takes a single actual parameter (usually a double-precision floating-point number) and returns the smallest integer that is greater than or equal to that actual parameter (rounding up)
round() Takes a single actual parameter (typically a double-precision floating-point number) and returns the nearest integer
abs() The absolute value of a number. If the only numeric actual parameter has a negative value, then the function returns the corresponding positive number; if the actual parameter is positive, then the function returns the actual parameter itself
min() Accepts any number of numeric actual parameters (but at least one) and returns the smallest of all actual parameter values
max() Accepts any number of numeric actual parameters (but not less than one) and returns the largest of all actual parameter values

For example, the result of the following expression is 3 because the value of each function call expression is also 3:

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

Generating random numbers

The PHP language uses two random number generators (called respectively using the functions rand() And mt_rand()). Each of these generators is associated with three functions of the same purpose: the function of setting the initial value ( srand() And mt_srand()), the function itself for obtaining a random number and the function that samples the largest integer that can be returned by the generator (( getrandmax() And mt_getrandmax())). The getrandmax() and mt_getrandmax() functions return a value the largest number, which can be returned by rand() or mt_rand(), on Windows platforms this value is limited to 32768.

Selecting a specific generation function pseudorandom numbers, which is used in the rand() function, may depend on which libraries the PHP interpreter was compiled with. In contrast, the mt_rand() generator always uses the same pseudo-random number generation function (mt is short for Mersenne Twister), and the author of the operational documentation for the mt_rand() function claims that this function is also faster and " more random" (from a cryptographic point of view) than rand(). We have no reason to doubt the truth of these statements, which is why we prefer to use the mt_rand() function rather than rand().

When using some versions of PHP on some platforms, it appears that the rand() and mt_rand() functions produce seemingly reasonable random numbers, even without first setting a seed. But such an impression should not be trusted. Firstly, programs that use functions for generating random numbers without specifying an initial value cannot be easily transferred to other platforms, and, secondly, the reliable operation of these functions without specifying an initial value is not guaranteed.

A typical way to set the initial value for any of the random generators PHP numbers(using the mt_srand() or srand() function) is as follows:

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

This operator sets the initial value of the generator, equal to the number of microseconds that have elapsed by this time since the last whole second was counted. (The cast to double in this statement is actually necessary because the microtime() function returns a string, which is treated as an integer in the multiplication operation but not in the operation of passing parameters to the function.) We recommend that the reader enter the specified initialization operator even if the purpose of this operator is not entirely clear to him; just enough to place this operator for each PHP page, just once, before using the corresponding mt_rand() or rand() function, and this operator will ensure that the starting point changes and therefore produces different random sequences each time.

The specific method setting the initial value was deeply thought out by those specialists who fully understand all the nuances of generating pseudo-random numbers, therefore, most likely, it will forever remain better than any attempts by any individual programmer to come up with something more “tricky”.

Obviously, these pseudo-random number generating functions only return integers, but a random integer from a given range can easily be converted to a corresponding floating-point number (say, a number from the range 0.0 to 1.0 inclusive) using an expression like rand() / getrandmax(). The specified range can then be scaled and shifted as needed. Below is an example:

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

Try refreshing the page with this code several times to ensure that random numbers are generated.

Mathematical constants

In PHP version 4.0, there was only one mathematical constant described in the documentation - M_PI (the value of π, represented as a double-precision floating-point number). And starting from PHP versions 4.0.2 many new constants were introduced. Most of these new constants related to π (or its multiples), e (or its multiples), and square roots; in addition, some constants belonged to other types. But in subsequent releases, for a number of reasons, the list of constants was again reduced to a relatively small number of predefined 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 number format

The PHP language provides a number of functions that allow you to check the correct representation of numbers. Although PHP does not have strict type checking, it is recommended that you implement some of these checks in your code when necessary to be able to predict the characteristics of the results you receive, and also to select best way their processing.

First and most simple check is to use the function is_numeric(). As with most other such tests, the is_numeric function returns a Boolean result - true if the parameter passed to it is numeric data of any type (signed or unsigned, integer or floating point) or a mathematical expression that returns a valid numeric value.

Using functions is_int() And is_float You can determine whether a number is an integer or a fraction. Two more checks are a little more complex: functions is_finite() And is_infinite() allow you to perform exactly the tests that their names indicate (whether the number is finite or infinite). But, strictly speaking, the range of values ​​over which these functions extend cannot include actual infinity (and can it even be checked whether the number has infinity? great importance?). Instead, the limits of the range of floating point values ​​allowed on the particular system are used.

Below is an example of using 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 - this check stricter than is_numeric() is_float(4); // false is_float(4.0); // true is_float(M_PI); // true

Conversion of number systems

Default in PHP language for forward and reverse conversion numerical values radix 10 is used from the external representation to the internal representation. In addition, you can tell the PHP interpreter that the external representation uses octal numbers, specified in base 8 (for this you must enter a leading 0 before the number), or hexadecimal numbers, specified in base 16 (for this, you must enter the prefix 0x before the number).

Of course, after converting numbers from an external representation to an internal one, they are stored in memory in binary format, and all basic arithmetic and mathematical calculations are carried out in the operating system in base 2. In addition, PHP provides a number of functions for converting numbers from one base to another. General information These functions are shown in the table below:

Number system conversion functions
Function Description
BinDec() Takes a single string parameter that is a binary integer (a base 2 number) and returns the base 10 string representation of that number
DecBin() Similar to BinDec(), but converts from base 10 to base 2
OctDec() Similar to BinDec(), but converts from base 8 to base 10
DecOct() Similar to BinDec(), but converts from base 10 to base 8
HexDec() Similar to BinDec(), but converts from base 16 to base 10
DecHex() Similar to BinDec(), but converts from base 10 to base 16
base_convert() Accepts a string parameter (representing the integer to be converted) and two integer parameters (the original and the desired radix). Returns a string representing the converted number. In this line, numbers greater than 9 (10 to 35) are represented symbols a-z. Both the original and desired bases must be within the range of 2-36

All number system conversion functions are special-purpose functions that convert numbers from one specific base to another. An exception is the base_convert() function, which accepts arbitrary parameters indicating the initial and resulting bases.

Note that all number system conversion functions accept string parameters and return string values, but you can use decimal numeric parameters and rely on the PHP interpreter to perform the type conversion correctly. In other words, both DecBin("1234") and DecBin(1234) both produce the same result.

Exponents and logarithms

The PHP language includes standard exponential and logarithmic functions in two varieties - for working in base 10 and base e (which are shown in the table).

PHP provides an exp() function to raise e to a given power, but there is no one-parameter function to raise 10 to a given power. However, you can use the pow() function instead, which takes two parameters, giving 10 as the first parameter.

You can verify that exponential and logarithmic functions with the same base are inverses of each other by checking the identity of the results obtained in this way:

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

The PHP language provides a standard set of basic trigonometric functions, general information about which is given in the table:

Trigonometric functions
Function Description
pi() It takes no parameters and returns an approximate value of π (3.1415926535898). Can be used interchangeably with the M_PI constant
sin() Accepts a numeric parameter in radians and returns the sine of the parameter as a double precision floating point number
cos() Takes a numeric parameter in radians and returns the cosine of the parameter as a double precision floating point number
tan() Accepts a numeric parameter in radians and returns the tangent of the parameter as a double precision floating point number
asin() Takes a numeric parameter and returns the arcsine of the parameter in radians. Inputs must be between -1 and 1 (the function receiving inputs outside this range results in a NAN result). The results range from -π/2 to π/2
acos() Takes a numeric parameter and returns the arc cosine of the parameter in radians. Inputs must be in the range -1 to 1 (the function receiving inputs outside this range results in a NAN result. Results are in the range 0 to π
atan() Takes a numeric parameter and returns the arctangent of the parameter in radians. The results range from -π/2 to π/2

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

PHP code function display_trigonometry($func_array, $input_array) ( // Function header echo " "; ) echo ""; // Print the rest of the table foreach($input_array as $input) ( echo " "; foreach($func_array as $func) ( echo " "; ) echo ""; ) echo "
Meaning/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));

An example of using trigonometric functions in PHP

The reason for obtaining very large (but not infinite) tangent values ​​is that the denominators should theoretically be zero, but in reality are slightly different from zero due to rounding errors.

Arbitrary precision calculation (using BC functions)

Integer and double-precision floating-point types are perfectly adequate for most math problems encountered in web scripting, but each instance of the value represented by these types requires a fixed amount of computer memory, so the size and precision of the number representation these types inevitably impose limitations.

Of course, the exact value ranges of these data types may depend on the architecture of the server computer, but integer values ​​can typically range from -2 31 -1 to 2 31 -1, and double-precision floating-point numbers can represent numbers with a precision of about 13 to 14 decimal digits. On the other hand, to solve problems that require the use of a wider range of representation or greater precision, PHP provides arbitrary precision mathematical functions(also called BC functions, named after the Unix-based arbitrary-precision computing utility).

You may find that arbitrary precision functions are not included in the compilation PHP interpreter, especially if the user carried out such compilation independently, since for this the user had to know that at the configuration stage it is necessary to include a checkbox in the parameters --enable-bcmath. To check whether the specified functions are available, try evaluating the expression bcadd("1","1"). If you receive an error message that states an undefined function, you will need to reconfigure the PHP interpreter and recompile it.

BC functions use strings rather than fixed-length numeric types as parameters and return values. Since in PHP the length of strings is limited only by the size available memory, the numbers used in the calculations can be of any length. The basic calculations are done in decimal form and are much like those that a person can do with pencil and paper (if he can work very quickly and be patient). BC functions that operate on integers are precise and allow you to use as many digits as you need, while BC functions that operate on floating point numbers are accurate to the specified number decimal places. General information about BC functions is given in the table below:

Arbitrary precision mathematical functions (BC functions)
Function Description
bcadd() Accepts two string parameters representing numbers and an optional integer parameter indicating a scale factor. Returns the sum of the first two parameters as a string, with the number of decimal places in the result determined by the parameter indicating the scale factor. If the parameter indicating the scale factor is not specified, then the default scale factor is used
bcsub() Similar to bcadd(), except that it returns the result of subtracting the second parameter from the first
bcmui() Similar to bcadd(), except that it returns the result of multiplying its parameters
bcdiv() Similar to bcadd(), except that it returns the result of dividing the first parameter by the second
bcmod() Returns the modulus (remainder) of dividing the first parameter by the second. Because the return value is an integer, the function does not accept a parameter indicating a scale factor
bcpow() Raises the first parameter to the power specified by the second parameter. The number of decimal places in the result is determined by the scale factor, if one is specified
bcsqrt() Returns the square root of the parameter with the number of decimal places determined by the value of the optional scale factor
bcscale() Sets the default scale factor for subsequent calls to the BC function

Most of these functions take as the last parameter an optional scale factor (an integer), which determines how many decimal places the result should have. If this parameter is not specified, the default scale factor is used as the scale factor, which in turn can be set by calling the bcscale() function. The default value for this default value (that is, the value that is used if the script does not call bcscale()) can also be set in the php.ini initialization file.

Below is an example of using an arbitrary precision function to perform integer arithmetic operations accurately. Executing the following code:

PHP code for ($x = 1; $x< 25; $x++) { echo "$x$x= ".bcpow($x, $x)."
"; }
Accurate calculation of astronomical quantities using BC functions

If a regular PHP integer type were used for these calculations, then the integer overflow would occur long before the end of the calculation, so the rest of the loop would perform calculations to obtain an approximate floating point number.

Arrays Form processing 1 2 3 4 5 6 7 8 9 10

This topic is important because almost all applications involve some kind of computing operations. Operations on numbers are presented in the table below.

Arithmetic operations in php

I think these operators don't need much explanation. I will give an example of using each of them:

\$num2 = ". $num2; //Example of summation: echo "
\$num1 + \$num2 = ". ($num1 + $num2); //Example of subtraction: echo "
\$num1 - \$num2 = ". ($num1 - $num2); //Multiplication example: echo "
\$num1 * \$num2 = ". $num1 * $num2; //Example of division: echo "
\$num1: \$num2 = ". $num1 / $num2; //Example of remainder from division: echo "
\$num1 % \$num2 = ". $num1 % $num2; //Example of incrementing in prefix form: echo "
++\$num1 = ". ++$num1; //Now $num1 = 11 $num1=10; //assigned initial value //Example of incrementing in post prefix form: echo "
\$num1++ = ". $num1++; //Now $num1 = 11 $num1=10; //assigned the original value //An example of decrementation in prefix form: echo "
--\$num1 = ". --$num1; $num1=10; //An example of decrementation in post-prefix form: echo "
\$num1-- = ". $num1--; ?>

The result of executing the above code:

$num1 = 10
$num2 = 7
$num1 + $num2 = 17
$num1 - $num2 = 3
$num1 * $num2 = 70
$num1: $num2 = 1.42857142857
$num1 % $num2 = 3
+$num1 = 11
$num1++ = 10
--$num1 = 9
$num1-- = 10

Difference between prefix and postprefix form:

  • in prefix form(++ is in front of the variable) first it is incremented by one, and then the result is printed
  • in postprefix form(++ comes after the variable) the result is first displayed, and then incremented

So that you can better understand the difference, I will give classic example, which is given in many programming textbooks:

//Assign values ​​to variables:$num1 = 10; $num2 = 7; $rez = ++$num1 + $num2; // result will be 18 echo "
\$rez = ". $rez; //Assign $num1 to the initial value:$num1 = 10; $rez = $num1++ + $num2; // the result will be 17 echo "
\$rez = ". $rez; //Operations ++ and -- can also be applied to strings$str = "abc"; echo "
".++$str; // the result will be the string "abd" ?>

It is worth noting that when adding variables, you can use two types of records:

  • $num1 = $num1 + $num2 - regular entry;
  • $num1 += $num2 is a shorthand notation. The result of these operations will be the same. Shorthand notation can also be used with subtractions and multiplications.

Comparison operators in php

Comparison operators are used in tests of if conditions and the like. However, in this lesson we will not cover conditional statements, but consider only comparison operators. All comparison operators are shown in the table below:

There is nothing complicated here, the principle is the same as in mathematics. The only peculiarity is that true is 1, and false is 0. Let's give detailed example in PHP:

//Assign values ​​to variables:$num1 = 10; $num2 = 7; echo "\$num1 > \$num2 = ". ($num1 > $num2); //get 1 (10 > 7 - true) echo "\$num1 //get 0 (10 //You can write it simpler: echo "
10 // 0 echo "
20 // 0 echo "
1 == 1 = ". (1 == 1); // 1 echo "
0 == \"\" = ". (0 == ""); // 1 echo "
0 === 0 = ". (0 === 0); // 1 echo "
0 === \"\" = ". (0 === ""); // 0 echo "
true = ". true; // 1 echo "
false = ". false; // 0 ?>

note:

  • If false, 0 will not be output
  • The equivalence operator returns 1 only if there is an exact match. For example, 0 == "" is true, but 0 === "" is no longer true, since there is no exact match.

Operations with PHP variables (operators)

There are various groups for implementation.

An operator is something consisting of one or more values ​​(expressions in programming jargon) that can be evaluated as a new value (thus, the entire construct can be considered an expression). It follows that functions or any other constructs that return a value (for example, print()) are operators, unlike all other language constructs (for example, echo()), which return nothing.

Arithmetic operations in PHP

Remember school basics of arithmetic? The statements below work the same way.

The division operator ("/") always returns a real type, even if both values ​​were integers (or strings that convert to integers). Otherwise, the result will be fractional.

The operation of calculating the remainder of division " % " only works with whole numbers, so applying it to fractions may produce undesirable results.

It is possible to use parentheses. The precedence of certain mathematical operations over others and the change in priorities when using parentheses in arithmetic expressions follow the usual rules of mathematics.

Increment and decrement operations

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

Postfix increment and decrement operators

As in C, these operators increment or decrement the value of a variable, and in an expression return the value of the variable $a before the change. For example:

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

As you can see, first the variable $b value assigned to variable $a, and only then the last one was incremented. However, the expression whose value is assigned to the variable $b, may be more difficult - in any case, increment $a will happen only after it has been calculated.

Prefix increment and decrement operators

There are also increment and decrement operators, which are specified rather than after the variable name. Accordingly, they return the value of the variable after the change. Example:

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

Increment and decrement operations are used very often in practice. For example, they occur in almost any cycle for .

echo "

Postfix increment

" ;
$a = 5 ;
echo "Should be 5: " . $a++ . "
\n" ;

\n" ;

Echo "

Prefix increment

" ;
$a = 5 ;
echo "Must be 6: " . ++ $a . "
\n" ;
echo "Must be 6: " . $a . "
\n" ;

Echo "

Postfix decrement

" ;
$a = 5 ;
echo "Should be 5: " . $a -- . "
\n" ;

\n" ;

Echo "

Prefix decrement

" ;
$a = 5 ;
echo "Must be 4: " . -- $a . "
\n" ;
echo "Must be 4: " . $a . "
\n" ;
?>

String operations

PHP has two operators for working with strings. The first is the concatenation operator ("."), which returns the concatenation of the left and right arguments. The second is an assignment operator with concatenation, which appends the right argument to the left one. Let's give a specific example:

$a = "Hello" ;
$b = $a . "World!" ; // $b contains the string "Hello World!"

$a = "Hello" ;
$a .= "World!" ; // $a contains the string "Hello World!"
?>

Bitwise operations

These operations are designed to operate (set/unset/check) groups of bits in an entire variable. The bits of an integer are nothing more than individual digits of the same number written in the binary number system. For example, in binary the number 12 would look like 1100 and 2 would look like 10, so the expression 12|2 will return us the number 14 (1110 in binary notation). If a variable is not an integer, then it is
first rounded, and then the following operators are applied to it.

To represent one number, 32 bits are used:

  • 0000 0000 0000 0000 0000 0000 0000 0000 is zero;
  • 0000 0000 0000 0000 0000 0000 0000 0001 is 1;
  • 0000 0000 0000 0000 0000 0000 0000 0010 is 2;
  • 0000 0000 0000 0000 0000 0000 0000 0011 is 3;
  • 0000 0000 0000 0000 0000 0000 0000 0100 is 4;
  • 0000 0000 0000 0000 0000 0000 0000 0101 is 5;
  • 0000 0000 0000 0000 0000 0000 0000 1111 is 15;

Bitwise operators:

Example Name Result
$a & $b Bitwise "and" Only those bits that are set in both $a and $b are set.
$a | $b Bitwise "or" Those bits that are set in either $a or $b are set.
$a^$b Exclusive or Only those bits that are set in either $a only or $b only are set
~$a Negation Those bits that are not set in $a are set, and vice versa.
$a<< $b Shift left All bits of variable $a are shifted $b positions to the left (each position implies a "multiply by 2")
$a >> $b Shift right All bits of variable $a are shifted $b positions to the right (each position implies "division by 2")

Comparison Operations

Comparison operators, as their name suggests, allow you to compare two values.

These are unique operations in their own way because, regardless of the types of their arguments, they always return one of two things: false or true. Comparison operations compare two values ​​with each other and, if the condition is true, return true, And if not - false.

PHP only allows scalar variables to be compared. Arrays and objects cannot be compared in PHP. They cannot even be compared for equality (using the == operator), but PHP does not issue a warning when performing such an operation. So, having once wondered why two completely different arrays when comparing them using == suddenly turn out to be the same, remember that before comparison both operands are converted to a word array, which is then compared.

See Array comparison for details.

Comparison operators:

Example Name Result
$a == $b Equals TRUE if $a is equal to $b.
$a === $b Identically equal TRUE if $a is equal to $b and has the same type. (Added in PHP 4)
$a != $b Not equal TRUE if $a is not equal to $b.
$a<>$b Not equal TRUE if $a is not equal to $b.
$a !== $b Identical is not equal TRUE if $a is not equal to $b or if they are of different types (Added in PHP 4)
$a< $b Less TRUE if $a is strictly less than $b.
$a > $b More TRUE if $a is strictly greater than $b.
$a<= $b Less or equal TRUE if $a is less than or equal to $b.
$a >= $b More or equal TRUE if $a is greater than or equal to $b.

Logical operations

Logical operators are designed exclusively for working with Boolean expressions and also return false or true.

Here is a table of PHP logical operators:

It should be noted that the evaluation of logical expressions containing such operators always proceeds from left to right, and if the result is already obvious (for example, false&&something always gives false), then the calculations are terminated, even if the expression contains function calls. For example, in the operator $logic = 0&&(time()>100); standard function time() will never be called.

Be careful with logical operations - don't forget about character doubling. Please note that, for example, | And || - two completely different operators, one of which can potentially return any number, and the second - only false And true.

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

Equivalence operators

In PHP, starting from PHP4 there is an identical comparison operator - a triple equal sign === ,
or the check operator. PHP is fairly tolerant of strings being implicitly converted to numbers, and vice versa.
For example, the following code will print that the values ​​of the variables are equal:

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

And this despite the fact that the variable $a represents a number and $b- line. Now let's look at a slightly different example:

$a=0; // zero
$b=""; // empty line
if($a==$b) echo "a and b are equal"; // Prints "a and b are equal"

Although $a And $b are clearly not equal even in the usual sense of the word, the script will declare that they are the same. Why is this happening? The point is that if one of the operands of a logical operator can be interpreted as a number, then both operands are treated as numbers. In this case, the empty line turns into 0 , which is then compared to zero. It is not surprising that the operator echo works.
The problem is solved by the equivalence operator === (triple equality). It not only compares two expressions, but also their types. Let's rewrite our example using this operator.

Logical operations exist in all programming languages ​​and PHP not an exception. In addition to simple division, multiplication, addition or subtraction, there are also integer and remainder divisions, which we will now talk about and also analyze them using detailed examples.

Integer division is the output of the integer part from the division. For example, if we divide 5 by 2, we get 2, not 2.5.

With residual division everything is different. This is the output of the remainder when divided by an integer. For example, dividing the same five, you will get not 2, but 1, because dividing 5 by 2, we get 2, and the remainder is 1.

How to do integer division in PHP

For example, in Python this division is done using a simple operator: "//".

And in PHP this will not be so easy to do, but still the process does not require super knowledge of the language.

Let's give an example of how this can be implemented.

IN PHP The seventh version of the function looks like this:

Intdiv();

In an older version, the same function looks like this:

There is also a method for all versions:

Floor();

How to apply?

For example, let's take the first function, all the others are performed in approximately the same way.

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

Remainder division in PHP

To display the integer remainder of division in PHP It's enough to just use the "%" operator.

$i = 10% 3; echo $i;

As we can see, everything is quite simple and does not require lengthy explanations.

Where can it be used?

Knowledge of integer division PHP will be very useful if you need to compare two numbers, create an inverted number (a popular exercise), or, for example, a program called FizzBuzz. Its essence is that you have to write a cycle from 1 to 100, which divides each number by 3 and 5. If the number divided by 3 has a remainder of 0, then we write Fizz, if divided by 5, then Buzz, and if , dividing both 5 and 3, the remainder is 0, then we write FizzBuzz. This is a very popular interview task. If you completed it yourself, you can be proud of yourself.

Or, for example, we have to derive all its numbers (4, 5, 2) from the number 452.

Conclusion

Of course, integer and remainder divisions are useful and quite common; they are not as convenient to use as in Python, but they are still important.

Now you are one step closer to learning a programming language PHP and in the future you will become even closer if you overcome difficulties just as diligently.







2024 gtavrl.ru.