Виды операций в php

Виды операций в php

Помните школьные основы арифметики? Описанные ниже операторы работают так же.

Арифметические операции

Пример Название Результат
+$a Идентичность Конвертация $a в int или float , что более подходит.
-$a Отрицание Смена знака $a .
$a + $b Сложение Сумма $a и $b .
$a — $b Вычитание Разность $a и $b .
$a * $b Умножение Произведение $a и $b .
$a / $b Деление Частное от деления $a на $b .
$a % $b Деление по модулю Целочисленный остаток от деления $a на $b .
$a ** $b Возведение в степень Возведение $a в степень $b .

Операция деления («/») возвращает число с плавающей точкой, кроме случая, когда оба значения являются целыми числами (или строками, которые преобразуются в целые числа), которые делятся нацело — в этом случае возвращается целое значение. Для целочисленного деления используйте intdiv() .

При делении по модулю операнды преобразуются в целые числа ( int ) (путём удаления дробной части) до начала операции. Для деления по модулю чисел с плавающей точкой используйте fmod() .

Результат операции остатка от деления % будет иметь тот же знак, что и делимое — то есть, результат $a % $b будет иметь тот же знак, что и $a . Например:

echo ( 5 % 3 ). «\n» ; // выводит 2
echo ( 5 % — 3 ). «\n» ; // выводит 2
echo (- 5 % 3 ). «\n» ; // выводит -2
echo (- 5 % — 3 ). «\n» ; // выводит -2

Источник

Операторы

Оператором называется нечто, принимающее одно или более значений (или выражений, если говорить на жаргоне программирования), и вычисляющее новое значение (таким образом, вся конструкция может рассматриваться как выражение).

Операторы можно сгруппировать по количеству принимаемых ими значений. Унарные операторы принимают только одно значение, например, ! (оператор логического отрицания) или ++ (инкремент). Бинарные операторы принимают два значения; это, например, знакомые всем арифметические операторы + (плюс) и — (минус), большинство поддерживаемых в PHP операторов входят именно в эту категорию. Ну и, наконец, есть всего один тернарный оператор, ? : , принимающий три значения, обычно его так и называют — «тернарный оператор» (хотя, возможно, более точным названием было бы «условный оператор»).

Полный список PHP-операторов вы можете найти в разделе «Порядок выполнения операторов». В этом разделе также описан порядок выполнения операторов и их ассоциативность, которые точно определяют, как вычисляются выражения с несколькими разными операторами.

User Contributed Notes 9 notes

of course this should be clear, but i think it has to be mentioned espacially:

’cause || has got a higher priority than and, but less than &&

of course, using always [ && and || ] or [ AND and OR ] would be okay, but than you should at least respect the following:

the first code will set $a to the result of the comparison $b with $c, both have to be true, while the second code line will set $a like $b and THAN — after that — compare the success of this with the value of $c

maybe usefull for some tricky coding and helpfull to prevent bugs 😀

Operator are used to perform operation.

Читайте также:  Php класс работы базой данных

Operator are mainly divided by three groups.
1.Uniary Operators that takes one values
2.Binary Operators that takes two values
3.ternary operators that takes three values

Operator are mainly divided by three groups that are totally seventeen types.
1.Arithmetic Operator
+ = Addition
— = Subtraction
* = Multiplication
/ = Division
% = Modulo
** = Exponentiation

2.Assignment Operator
= null coalescing

14.Clone new Operator
clone new = clone new

16.yield Operator
yield = yield

17.print Operator
print = print

Other Language books’ operator precedence section usually include «(» and «)» — with exception of a Perl book that I have. (In PHP «<" and ">» should also be considered also). However, PHP Manual is not listed «(» and «)» in precedence list. It looks like «(» and «)» has higher precedence as it should be.

Note: If you write following code, you would need «()» to get expected value.

$bar = true ;
$str = «TEST» . ( $bar ? ‘true’ : ‘false’ ) . «TEST» ;
?>

Without «(» and «)» you will get only «true» in $str.
(PHP4.0.4pl1/Apache DSO/Linux, PHP4.0.5RC1/Apache DSO/W2K Server)
It’s due to precedence, probably.

The variable symbol ‘$’ should be considered as the highest-precedence operator, so that the variable variables such as $$a[0] won’t confuse the parser. [http://www.php.net/manual/en/language.variables.variable.php]

If you use «AND» and «OR», you’ll eventually get tripped up by something like this:

$this_one = true ;
$that = false ;
$truthiness = $this_one and $that ;
?>

Want to guess what $truthiness equals?

If you said «false» . it’s wrong!

«$truthiness» above has the value «true». Why? «=» has a higher precedence than «and». The addition of parentheses to show the implicit order makes this clearer:

( $truthiness = $this_one ) and $that ;
?>

If you used «&&» instead of and in the first code example, it would work as expected and be «false».

This also works to get the correct value, as parentheses have higher precedence than » default»>$truthiness = ( $this_one and $that );
?>

Note that in php the ternary operator ?: has a left associativity unlike in C and C++ where it has right associativity.

You cannot write code like this (as you may have accustomed to in C/C++):

$a = 2 ;
echo (
$a == 1 ? ‘one’ :
$a == 2 ? ‘two’ :
$a == 3 ? ‘three’ :
$a == 4 ? ‘four’ : ‘other’ );
echo «\n» ;
// prints ‘four’
?>

You need to add brackets to get the results you want:

echo ( $a == 1 ? ‘one’ :
( $a == 2 ? ‘two’ :
( $a == 3 ? ‘three’ :
( $a == 4 ? ‘four’ : ‘other’ ) ) ) );
echo «\n» ;
//prints ‘two’
?>

The scope resolution operator . which is missing from the list above, has higher precedence than [], and lower precedence than ‘new’. This means that self::$array[$var] works as expected.

A quick note to any C developers out there, assignment expressions are not interpreted as you may expect — take the following code ;-

$a =array( 1 , 2 , 3 );
$b =array( 4 , 5 , 6 );
$c = 1 ;

print_r ( $a ) ;
?>

This will output;-
Array ( [0] => 1 [1] => 6 [2] => 3 )
as if the code said;-
$a[1]=$b[2];

Under a C compiler the result is;-
Array ( [0] => 1 [1] => 5 [2] => 3 )
as if the code said;-
$a[1]=$b[1];

It would appear that in php the increment in the left side of the assignment is processed prior to processing the right side of the assignment, whereas in C, neither increment occurs until after the assignment.

Читайте также:  Make forms with html

A variable is a container that contain different types of data and the operator operates a variable correctly.

  • Справочник языка
    • Основы синтаксиса
    • Типы
    • Переменные
    • Константы
    • Выражения
    • Операторы
    • Управляющие конструкции
    • Функции
    • Классы и объекты
    • Пространства имён
    • Перечисления
    • Ошибки
    • Исключения
    • Fibers
    • Генераторы
    • Атрибуты
    • Объяснение ссылок
    • Предопределённые переменные
    • Предопределённые исключения
    • Встроенные интерфейсы и классы
    • Предопределённые атрибуты
    • Контекстные опции и параметры
    • Поддерживаемые протоколы и обёртки

    Источник

    PHP Operators

    Operators are used to perform operations on variables and values.

    PHP divides the operators in the following groups:

    • Arithmetic operators
    • Assignment operators
    • Comparison operators
    • Increment/Decrement operators
    • Logical operators
    • String operators
    • Array operators
    • Conditional assignment operators

    PHP Arithmetic Operators

    The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as addition, subtraction, multiplication etc.

    Operator Name Example Result Show it
    + Addition $x + $y Sum of $x and $y Try it »
    Subtraction $x — $y Difference of $x and $y Try it »
    * Multiplication $x * $y Product of $x and $y Try it »
    / Division $x / $y Quotient of $x and $y Try it »
    % Modulus $x % $y Remainder of $x divided by $y Try it »
    ** Exponentiation $x ** $y Result of raising $x to the $y’th power Try it »

    PHP Assignment Operators

    The PHP assignment operators are used with numeric values to write a value to a variable.

    The basic assignment operator in PHP is «=». It means that the left operand gets set to the value of the assignment expression on the right.

    Assignment Same as. Description Show it
    x = y x = y The left operand gets set to the value of the expression on the right Try it »
    x += y x = x + y Addition Try it »
    x -= y x = x — y Subtraction Try it »
    x *= y x = x * y Multiplication Try it »
    x /= y x = x / y Division Try it »
    x %= y x = x % y Modulus Try it »

    PHP Comparison Operators

    The PHP comparison operators are used to compare two values (number or string):

    Operator Name Example Result Show it
    == Equal $x == $y Returns true if $x is equal to $y Try it »
    === Identical $x === $y Returns true if $x is equal to $y, and they are of the same type Try it »
    != Not equal $x != $y Returns true if $x is not equal to $y Try it »
    <> Not equal $x <> $y Returns true if $x is not equal to $y Try it »
    !== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type Try it »
    > Greater than $x > $y Returns true if $x is greater than $y Try it »
    Less than $x < $y Returns true if $x is less than $y Try it »
    >= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y Try it »
    Less than or equal to $x Returns true if $x is less than or equal to $y Try it »
    Spaceship $x $y Returns an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or greater than $y. Introduced in PHP 7. Try it »

    PHP Increment / Decrement Operators

    The PHP increment operators are used to increment a variable’s value.

    The PHP decrement operators are used to decrement a variable’s value.

    Operator Name Description Show it
    ++$x Pre-increment Increments $x by one, then returns $x Try it »
    $x++ Post-increment Returns $x, then increments $x by one Try it »
    —$x Pre-decrement Decrements $x by one, then returns $x Try it »
    $x— Post-decrement Returns $x, then decrements $x by one Try it »

    PHP Logical Operators

    The PHP logical operators are used to combine conditional statements.

    Operator Name Example Result Show it
    and And $x and $y True if both $x and $y are true Try it »
    or Or $x or $y True if either $x or $y is true Try it »
    xor Xor $x xor $y True if either $x or $y is true, but not both Try it »
    && And $x && $y True if both $x and $y are true Try it »
    || Or $x || $y True if either $x or $y is true Try it »
    ! Not !$x True if $x is not true Try it »

    PHP String Operators

    PHP has two operators that are specially designed for strings.

    Operator Name Example Result Show it
    . Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2 Try it »
    .= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1 Try it »

    PHP Array Operators

    The PHP array operators are used to compare arrays.

    Operator Name Example Result Show it
    + Union $x + $y Union of $x and $y Try it »
    == Equality $x == $y Returns true if $x and $y have the same key/value pairs Try it »
    === Identity $x === $y Returns true if $x and $y have the same key/value pairs in the same order and of the same types Try it »
    != Inequality $x != $y Returns true if $x is not equal to $y Try it »
    <> Inequality $x <> $y Returns true if $x is not equal to $y Try it »
    !== Non-identity $x !== $y Returns true if $x is not identical to $y Try it »

    PHP Conditional Assignment Operators

    The PHP conditional assignment operators are used to set a value depending on conditions:

    Operator Name Example Result Show it
    ?: Ternary $x = expr1 ? expr2 : expr3 Returns the value of $x.
    The value of $x is expr2 if expr1 = TRUE.
    The value of $x is expr3 if expr1 = FALSE
    Try it »
    ?? Null coalescing $x = expr1 ?? expr2 Returns the value of $x.
    The value of $x is expr1 if expr1 exists, and is not NULL.
    If expr1 does not exist, or is NULL, the value of $x is expr2.
    Introduced in PHP 7
    Try it »

    Источник

Оцените статью