Last updated: 1.11.2015

In PHP, we can use various operators: arithmetic, logical, etc. Let's consider each type of operation.

Arithmetic operations

    + (addition operation)

    For example, $ a + 5

    - (subtraction operation)

    For example, $ a - 5

    * (multiplication)

    For example, $ a * 5

    / (division)

    For example, $ a / 5

    % (get the remainder of the division)

    For example: $ a = 12; echo $ a% 5; // equals 2

    ++ (increment / increment value by one)

    For example ++ $ a

    It is important to understand the difference between ++ $ a and $ a ++. For example:

    $ a = 12; $ b = ++ $ a; // $ b is 13 echo $ b;

    Here, first one is added to the value of the variable $ a, and then its value is equated to the variable $ b. It would be different if the expression looked like this: $ b = $ a ++; ... Here, first the value of the variable $ a was equated to the variable $ b, and then the value of the variable $ a was increased.

    - (decrement / decrement value by one)

    For example - $ a. And just like in the case of the increment, there are two types of notation: - $ a and $ a--

Assignment operations

    Sets a variable to a specific value: $ a = 5

    Addition followed by assignment of the result. For example: $ a = 12; $ a + = 5; echo $ a; // equals 17

    Subtraction followed by assignment of the result. For example: $ a = 12; $ a - = 5; echo $ a; // equals 7

    Multiplication followed by assignment of the result: $ a = 12; $ a * = 5; echo $ a; // equals 60

    Division followed by assignment of the result: $ a = 12; $ a / = 5; echo $ a; // equals 2.4

    Concatenation of strings with result assignment. Applies to two lines. If the variables do not store strings, but, for example, numbers, then their values ​​are converted to strings and then the operation is performed: $ a = 12; $ a. = 5; echo $ a; // equal to 125 // identical to $ b = "12"; $ b. = "5"; // equals 125

    Getting the remainder from division with the subsequent assignment of the result: $ a = 12; $ a% = 5; echo $ a; // equals 2

Comparison operations

Comparison operations are usually used in conditional constructions when it is necessary to compare two values ​​and, depending on the result of the comparison, perform some actions. The following comparison operations are available.

    The equality operator compares two values ​​and if they are equal it returns true, otherwise it returns false: $ a == 5

    The identity operator also compares two values, and if they are equal, it returns true, otherwise it returns false: $ a === 5

    Compares two values, and if they are not equal, returns true, otherwise returns false: $ a! = 5

    Compares two values, and if they are not equal, returns true, otherwise returns false: $ a! == 5

    Compares two values, and if the first is greater than the second, it returns true, otherwise it returns false: $ a> 5

    Compares two values, and if the first is less than the second, it returns true, otherwise it returns false: $ a< 5

    Compares two values, and if the first is greater than or equal to the second, it returns true, otherwise it returns false: $ a> = 5

    Compares two values, and if the first is less than or equal to the second, it returns true, otherwise it returns false: $ a<= 5

Equality and Identity Operator

Both operators compare two expressions and return true if the expressions are equal. But there are differences between them. If two values ​​of different types are taken in the equality operation, then they are reduced to one - the one that the interpreter finds optimal. For example:

Obviously, variables store different values ​​of different types. But when compared, they will be reduced to the same type - numeric. And the variable $ a will be reduced to the number 22. And as a result, both variables will be equal.

Or, for example, the following variables will also be equal:

$ a = false; $ b = 0;

To avoid such situations, the equivalence operation is used, which takes into account not only the value, but also the type of the variable:

$ a = "22a"; $ b = 22; if ($ a === $ b) echo "equal"; else echo "not equal";

Now the variables will not be equal.

The inequality operators! = And! == work similarly.

Logical operations

Boolean operations are commonly used to combine the results of two comparison operations. For example, we need to perform a certain action if several conditions are true. The following logical operations are available:

    Returns true if both comparison operations return true, otherwise returns false: $ a == 5 && $ b = 6

    Similar to &&: $ a == 5 and $ b> 6

    Returns true if at least one comparison operation returns true, otherwise returns false: $ a == 5 || $ b = 6

    Similarly to the operation || : $ a< 5 or $b > 6

    Returns true if the comparison operation returns false:! ($ A> = 5)

    Returns true if only one of the values ​​is true. If both are true or neither is true, returns false. For example: $ a = 12; $ b = 6; if ($ a xor $ b) echo "true"; else echo "false";

    Here the result of the boolean operation will be false, since both variables have a certain value. Let's change the code:

    $ a = 12; $ b = NULL; if ($ a xor $ b) echo "true"; else echo "false";

    Here, the result will already be true, since the value of one variable is not set. If a variable is NULL, then in logical operations its value will be considered as false

Bitwise operations

Bitwise operations are performed on individual bits of a number. Numbers are considered in binary representation, for example, 2 in binary representation 010, number 7 - 111.

    & (logical multiplication)

    Multiplication is performed bit by bit, and if both operands have bit values ​​equal to 1, then the operation returns 1, otherwise the number 0 is returned. For example: $ a1 = 4; // 100 $ b1 = 5; // 101 echo $ a1 & $ b1; // equals 4

    Here the number 4 in the binary system is 100, and the number 5 is 101. We multiply the numbers bit by bit and get (1 * 1, 0 * 0, 0 * 1) = 100, that is, the number 4 in decimal format.

    | (logical addition)

    It looks like logical multiplication, the operation is also performed on binary digits, but now one is returned if at least one number in the given digit has a one. For example: $ a1 = 4; // 100 $ b1 = 5; // 101 echo $ a1 | $ b1; // equals 5

    ~ (logical negation)

    inverts all the digits: if the value of the digit is 1, then it becomes equal to zero, and vice versa. $ b = 5; echo ~ $ b;

    x<

    x >> y - shifts the number x to the right by y digits. For example, 16 >> 1 shifts the number 16 (which is 10,000 in binary) one digit to the right, that is, it ends up with 1000 or 8 in decimal

Concatenating strings

The dot operator is used to concatenate strings. For example, let's concatenate several lines:

$ a = "Hello,"; $ b = "world"; echo $ a. $ b. "!";

If the variables do not represent strings, but other types, for example, numbers, then their values ​​are converted to strings and then the string concatenation operation also occurs.

Logic 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 residual divisions, which we will now talk about, and also analyze them using detailed examples.

Integer division is the output of the integer part of 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 of a division by an integer. For example, dividing the same five, you get not 2, but 1, because dividing 5 by 2, we get 2, and the remainder remains 1.

How to perform integer division in PHP

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

And in PHP it will not be so easy to do this, but still the process does not require superfluous 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 way for all versions:

Floor ();

How to register?

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

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

Remaining division in PHP

To print the integer remainder of a division into PHP, just put the "%" operator.

$ i = 10% 3; echo $ i;

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

Where can you apply?

Knowledge of integer division in PHP will be very useful if you need to compare two numbers, create a flip 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 gives 0 in the remainder, then we write Fizz, if divided by 5, then Buzz, and if by dividing both 5 and 3, we get 0 in the remainder, then we write FizzBuzz. This is a very popular job interview. If you did it yourself, then you can be proud of yourself.

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

Conclusion

Of course, integer and residual divisions are useful and occur quite often, they are not as convenient to use as in Python, but still important.

You are now one step closer to learning a programming language PHP, and in the future, you will become even closer if you overcome difficulties with the same diligence.

All basic mathematical operations are available in PHP. Both integers and real numbers can be used as operands.

The table provides a list of arithmetic operators:
OperatorSignDescription
Addition + Adding two values
Subtraction - Subtracting one value from another
Multiplication * Multiplying two values
Division / Dividing one value by another
Obtaining the remainder of division % Dividing one value by another and returning the remainder (modulo division)
Increment ++ Abbreviated notation for increasing a number by one
Decrement -- Abbreviated notation for decreasing a number by one
Unary negation - Converting a positive number to negative or negative to positive

Subtraction, multiplication, division, modulo, and addition operators

The operators of subtraction, multiplication, division, modulo division, and addition are used in the same way as in mathematics. Here it is worth paying attention to the operators of division and division modulo.

The division operator ("/") returns a floating point number, unless both values ​​are integers (or strings that are converted to integers) that are evenly divisible, in which case an integer value is returned.

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

In modulo division, the operands are converted to integers (with the removal of the fractional part) before the operation begins. The result of the modulus% operation will have the same sign as the dividend:

Unary negation

The unary negation operator is denoted by the "-" sign, it changes the value of its only operand to the opposite:

In this case, the parentheses are unnecessary because unary negation has the highest precedence, but they help to organize the code so that it is clear that the numbers -5 and 4 are being added.

Increment

The increment operator, denoted by ++ and can be located on either side of the operand with which it operates. It increases this value by one, just like adding one to a value. The actual result depends on where the operator was applied, before or after the operand with which it was applied. This operator is often used with variables, and often it happens inside loops (about loops will be discussed later).

Increment prefix form

Prefix form- this is when the increment operator is located before the operand, this form of notation means that the increment will be performed first: it increases the value of the operand by one and only then the rest of the instruction is executed:

Postfix increment form

Postfix form written a little differently - the increment is located in this case after the operand. With the postfix form of notation, the first use of the operand returns its current value, only after that the value will be increased by one:

Decrement

The decrement operator, denoted by the - sign, and unlike the increment operator, decreases, rather than increases, by one the value of its operand. Decrement also allows prefix and postfix notation:

Programmers who need to do responsible numeric, scientific, or statistical computing are unlikely to consider a web scripting language as an acceptable candidate for this role. That said, PHP offers an excellent set of functions that fully address most of the math problems that arise in web scripting. In addition, PHP provides some more advanced features such as arbitrary precision arithmetic, hashing and cryptographic libraries.

The PHP developers took a well-grounded approach and did not attempt to reinvent the wheels for this purpose. The point is that many of the most fundamental mathematical functions used in PHP are simply wrappers around the C analogs of those functions.

Mathematical operations

Most of the math in PHP is done in the form of built-in functions, not operations. In addition to comparison operations, PHP offers five simple arithmetic operations, as well as some shorthand operations that allow you to construct shorter increment and decrement expressions, as well as assignments.

Arithmetic operations

The five basic arithmetic operations include those that are commonly found in any four-function calculator, as well as the modulo division (%) operation. A brief description of arithmetic operations is 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 this operand with the opposite sign
* Returns the product of the values ​​of its two operands
/ Returns the result of floating point division of the left operand value by the right operand value
% Returns the remainder of the integer division of the left operand value by the absolute value of the right operand

When using the first three above-described arithmetic operations (+, -, *) in the program, it should be borne in mind that when performing these operations, the type propagates from double-precision floating-point values ​​to integer values. This implies the following: if both operands of the 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. The same kind of propagation of type 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 complete.

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

Increment and decrement operations

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

The increment operation (++) is used to add one to the value of the variable to which this operation applies, and the decrement (-) operation subtracts one from the value of such a variable.

Each of these two operations has two flavors - suffix(in this form, the operation sign is placed immediately following the variable to which the operation applies) and prefix(in this form, the operation sign is placed immediately before the variable to which the operation applies). Both flavors have the same side effect of changing the value of a variable, but suffix and prefix operations return different values ​​when used as expressions. A suffix operation is such that the value of a variable changes after the expression is returned, and a prefix operation is such that the value is changed first and then a new value is returned to the variable. This difference can be discovered using the decrement and increment operations in the assignment operators:

PHP Code $ count = 0; $ result = $ count ++; echo "The result of the increment $ count ++:". $ result. "
"; $ count = 0; $ result = ++ $ count; echo" Increment result ++ $ count: ". $ result."
";

These operators generate the following output in the browser window:

Increment operations

In this example, the $ result = $ count ++ operator is fully 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 operations

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

PHP Code $ count = $ count * 3;

can be abbreviated as

PHP Code $ count * = 3;

Simple math functions

The next stage in the complication of the program in comparison with the one in which only arithmetic operations are used is to use all kinds of functions. Functions allow you to perform tasks such as converting from one numeric type to another (see the Data Types article) and finding the minimum or maximum number in a set of numbers. The following table presents simple math functions:

PHP Simple Math Functions
Function Description
floor () Takes a single actual parameter (usually a double precision floating point number) and returns the largest integer less than or equal to that actual parameter (round down)
ceil () The name of this function is short for 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 (usually 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 at least 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 expression with a function call is also 3:

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

Generating random numbers

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

The choice of the particular pseudo-random number generation function 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 online documentation for the mt_rand () function claims that this function is also faster and " more random "(in terms of cryptography) than rand (). We have no reason to doubt the truth of these statements, so we prefer to use the mt_rand () function over rand ().

When using some versions of PHP for some platforms, it seems that the rand () and mt_rand () functions generate seemingly perfectly acceptable random numbers, even without first specifying the initial value. But such an impression is not to be trusted. First, 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 seed for any of PHP's random number generators (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 since the last whole second. (Casting to double in this operator is really 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 initial value operator, even if he does not quite understand the purpose of this operator; simply put this statement on each PHP page, just once, before using the appropriate mt_rand () or rand () function, and this statement will ensure that the starting point changes and therefore a different random sequence is generated each time.

This particular method of setting the initial value has been deeply thought out by those experts who fully understand all the nuances of generating pseudo-random numbers, so it will most likely forever remain the best compared to any attempts by some individual programmer to come up with something more "intricate".

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

PHP Code // Let's say we need to generate a random number between 100.0 and 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 make sure it is generating random numbers.

Mathematical constants

In PHP 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 since PHP 4.0.2, many new constants have been introduced. Most of these new constants were for π (or multiples of it), e (or multiples of it), and square roots; in addition, some constants were of 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 math 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 log 2 (e)
M_LOG10E lg (e)
M_LN2 log e (2)
M_LN10 log e (10)

Number format check

PHP provides a number of functions that allow you to check the correctness of the representation of numbers. Although PHP lacks strong typing, it is recommended that you apply some of these checks in your code whenever you need to, to be able to predict the characteristics of the results you get and choose the best way to handle them.

The first and most straightforward check is to use the function is_numeric ()... As with most other such checks, is_numeric returns a Boolean result - true if the parameter passed to it is any type of numeric data (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 the number is integer or fractional. Two more checks are a little more complex: functions is_finite () and is_infinite () allow you to perform exactly the checks that their names indicate (whether the number is finite or infinite). But, strictly speaking, the range of values ​​covered by these functions cannot include actual infinity (and can it be verified at all if a number has an infinite value?). Instead, it uses the system-specific limits of the floating-point range.

An example of using these functions is shown below:

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 is stricter than the check using the is_numeric () function is_float (4); // false is_float (4.0); // true is_float (M_PI); // true

Number systems conversion

By default, PHP uses radix 10 for forward and backward conversion of numeric values ​​from external to internal representation. Alternatively, you can tell the PHP interpreter that the external representation uses octal numbers in base 8 (to do this, you must enter leading 0), or hexadecimal numbers specified in base 16 (to do 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 performed in the operating system itself in base 2. In addition, the PHP language provides a number of functions for converting numbers from one base of the system reckoning to another. An overview of these features is shown in the table below:

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

All number system conversion functions are special-purpose functions that convert numbers from one specific base to another. The exception is the base_convert () function, which accepts arbitrary parameters with the designation of the starting and resulting base.

Note that all numeric 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, the options for calling DecBin ("1234") and DecBin (1234) produce the same result.

Exponents and logarithms

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

PHP provides a function exp () to raise the number e to the specified power, but there is no function with one parameter that could be used to raise the number 10 to the specified power. However, instead of this function, you can use the function pow () with two parameters, giving 10 as the first parameter.

You can make sure that exponential and logarithmic functions with the same base are inverse with respect to 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

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

Trigonometric functions
Function Description
pi () Takes no parameters and returns an approximate value for π (3.1415926535898). Can be used interchangeably with the M_PI constant
sin () Takes 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 () Takes 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 inverse sine of the parameter in radians. Input data must be in the range from -1 to 1 (if the function receives input data outside this range, results in a NAN result). Results range from -π / 2 to π / 2
acos () Takes in a numeric parameter and returns the inverse cosine of the parameter in radians. Input data must be in the range from -1 to 1 (if the function receives input data outside this range, results in a NAN result. Results range from 0 to π
atan () Takes a numeric parameter and returns the arctangent of the parameter in radians. 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) (// echo function header " ";) echo""; // Print the rest of the table 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));

An example of using trigonometric functions in PHP

Obtaining very large (but not infinite) values ​​of the tangent is due to the fact that in theory the denominators should be equal to zero, but in reality they differ slightly from zero due to round-off errors.

Arbitrary Precision Calculation (Using BC Functions)

Double-precision integer and floating-point types are perfectly suitable for solving most of the mathematical problems that arise when executing scripts for the web, but there is a fixed amount of computer memory to store each instance of a value represented by these types, therefore, the size and precision of the representation of numbers restrictions are inevitably imposed on these types.

Of course, the exact ranges of these types of data 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 requiring a wider range of representation or greater precision, PHP provides arbitrary precision math functions(also called BC functions, after a Unix-based arbitrary precision computational utility).

It may turn out that functions with arbitrary precision are not included in the compilation of the PHP interpreter, especially if the user performed such compilation on his own, since for this the user had to know that during the configuration step it is necessary to include the checkbox in the parameters --enable-bcmath... To check if the specified functions are available, try evaluating the expression bcadd ("1", "1"). If you receive an error that says an undefined function, you will need to tweak the configuration again and recompile the PHP interpreter.

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 amount of available memory, the numbers used in the calculations can be of any length. Fundamental calculations are carried out in decimal form and are in many ways similar to those that a person can perform with a pencil and paper (if he can act very quickly and be patient). Integer BC functions are precise and allow you to use as many digits as you need, while floating-point functions perform calculations to the specified number of decimal places. An overview of the BC functions is shown in the table below:

Arbitrary-precision math functions (BC functions)
Function Description
bcadd () Accepts two string parameters representing numbers and an optional integer parameter with a scale factor designator. Returns the sum of the first two parameters as a string, with the number of decimal places in the result specified by the parameter with the scale factor notation. If the parameter with the scale factor designation 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. Since the return value is of an integer type, the function does not take a parameter with a scale factor notation
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 specified.
bcsqrt () Returns the square root of a parameter with the number of decimal places specified by the value of an optional scale factor
bcscale () Sets the default scaling factor for subsequent calls to the BC function

Most of these functions take an optional scale factor (integer) as the last parameter, which determines how many decimal places should be in the result. If no such parameter is specified, then 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 use the bcscale () function call) can also be set in the php.ini initialization file.

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

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

If the normal PHP integer type were used for these calculations, the integer overflow would occur long before the end of the calculation, so the rest of the loop would be done to get an approximate floating point number.

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