Операторы
Содержание
- Приоритет оператора
- Арифметические операторы
- Оператор присваивания
- Побитовые операторы
- Операторы сравнения
- Оператор управления ошибками
- Операторы исполнения
- Операторы инкремента и декремента
- Логические операторы
- Строковые операторы
- Операторы, работающие с массивами
- Оператор проверки типа
Оператором называется нечто, принимающее одно или более значений (или выражений, если говорить на жаргоне программирования), и вычисляющее новое значение (таким образом, вся конструкция может рассматриваться как выражение).
Операторы можно сгруппировать по количеству принимаемых ими значений. Унарные операторы принимают только одно значение, например, ! (оператор логического отрицания) или ++ (инкремент). Бинарные операторы принимают два значения; это, например, знакомые всем арифметические операторы + (плюс) и - (минус), большинство поддерживаемых в PHP операторов входят именно в эту категорию. Ну и, наконец, есть всего один тернарный оператор, ? :, принимающий три значения, обычно его так и называют -- "тернарный оператор" (хотя, возможно, более точным названием было бы "условный оператор").
Полный список PHP-операторов вы можете найти в разделе "Порядок выполнения операторов". В этом разделе также описан порядок выполнения операторов и их ассоциативность, которые точно определяют, как вычисляются выражения с несколькими разными операторами.
- Основы синтаксиса
- Типы
- Переменные
- Константы
- Выражения
- Операторы
- Управляющие конструкции
- Функции
- Классы и объекты
- Пространства имен
- Errors
- Исключения
- Generators
- Ссылки. Разъяснения
- Предопределённые переменные
- Предопределённые исключения
- Встроенные интерфейсы и классы
- Контекстные опции и параметры
- Поддерживаемые протоколы и обработчики (wrappers)
Коментарии
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.
<?php
$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.
of course this should be clear, but i think it has to be mentioned espacially:
AND is not the same like &&
for example:
<?php $a && $b || $c; ?>
is not the same like
<?php $a AND $b || $c; ?>
the first thing is
(a and b) or c
the second
a and (b or c)
'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:
<?php $a = $b && $c; ?>
<?php $a = $b AND $c; ?>
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 :D
greetz, Warhog
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. [language.variables.variable]
Operator are used to perform operation.
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
= "equal to
3.Array Operator
+ = Union
== = Equality
=== = Identity
!= = Inequality
<> = Inequality
!== = Non-identity
4.Bitwise Operator
& = and
^ = xor
| = not
<< = shift left
>> = shift right
5.Comparison Operator
== = equal
=== = identical
!= = not equal
!== = not identical
<> = not equal
< = less than
<= less than or equal
> = greater than
>= = greater than or equal
<=> = spaceship operator
6.Execution Operator
`` = backticks
7.Error Control Operator
@ = at sign
8.Incrementing/Decrementing Operator
++$a = PreIncrement
$a++ = PostIncrement
--$a = PreDecrement
$a-- = Postdecrement
9.Logical Operator
&& = And
|| = Or
! = Not
and = And
xor = Xor
or = Or
10.string Operator
. = concatenation operator
.= concatenating assignment operator
11.Type Operator
instanceof = instanceof
12.Ternary or Conditional operator
?: = Ternary operator
13.Null Coalescing Operator
??" = null coalescing
14.Clone new Operator
clone new = clone new
15.yield from Operator
yield from = yield from
16.yield Operator
yield = yield
17.print Operator
print = print
<?php
session_start();
// Datenbankverbindung etablieren
$servername = "mysql";
$username = "root";
$password = "htlkrems";
try {
// Instanz des PDO Objektes erzeugen
$conn = new PDO("mysql:host=$servername;dbname=classicmodels", $username, $password);
// PDO Error Mode auf Exception setzen
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connected successfully"; // Ausgabe wenn DB-Verbindung ok
} catch(PDOException $e) {
// Ausgabe der Fehlermeldung falls DB-Verbindung fehlgeschlagen
echo "Connection failed: " . $e->getMessage();
}
$inputText = "";
//Aufgabe 1:
if(isset($_POST["inp"])){
$_SESSION["input"] = $_POST["inp"];
}
$conn->query("SET FOREIGN_KEY_CHECKS = 0");
if(isset($_GET['id'])){
$delCode = $_GET['id'];
$stmt = $conn->query("DELETE FROM products WHERE productCode like '$delCode'");
}
if(isset($_GET['subDel'])) {
if (isset($_GET['del']) && is_array($_GET['del'])){
$delID = $_GET['del'];
foreach($delID as $del){
$stmt = $conn->query("DELETE FROM products WHERE productCode like '$del'");
}
}
}
if(isset($_SESSION["input"])){
$inputText = $_SESSION["input"];
$stmt = $conn->query("SELECT * FROM products WHERE productName like '$inputText%'");
}else{
$stmt = $conn->query("SELECT * FROM products"); // SQL Query ausführen
}
if(isset($_GET['productName'])){
$stmt = $conn->query("SELECT * FROM products ORDER BY productName"); // SQL Query ausführen
}
if(isset($_GET['scale'])){
$stmt = $conn->query("SELECT * FROM products ORDER BY productScale"); // SQL Query ausführen
}
if(isset($_GET['stock'])){
$stmt = $conn->query("SELECT * FROM products ORDER BY quantityInStock"); // SQL Query ausführen
}
if(isset($_GET['price'])){
$stmt = $conn->query("SELECT * FROM products ORDER BY buyPrice"); // SQL Query ausführen
}
$result = $stmt->fetchAll(PDO::FETCH_ASSOC); // alle Daten mit fetchAll fetchen -> Ergebnis ist ein 2-dimensionales Array
?>
<form action="index.php" method="post">
<?php
echo '<input type="text" name="inp" placeholder="Product Name" value="' . $inputText . '">';
?>
<button type="submit" name="subSearch">Submit</button>
</form>
<!-- STEP 1: Ausgabe des Array -->
<?php
// echo "<pre>"; print_r($result); echo "</pre>";
?>
<?php
foreach($result as $row) {
// Iteration über alle Datensätze -> Ergebnis ist ein 1-dimensionales assoziatives Array
// print_r($result); // Ausgabe des Arrays zu Testzwecken
echo "<tr>";
// Werte in einer Table-row ausgeben
echo "<td>" . $row['productName'] . "</td>";
echo "<td>" . $row['productScale'] . "</td>";
echo "<td>" . $row['quantityInStock'] . "</td>";
echo "<td>" . $row['buyPrice'] . "</td>";
// STEP 3: Link per mit GET auf einzelnen Datensatz
echo "<td><a href='?id=" . $row['productCode'] . "'>Löschen</a></td>";
echo "<td><input type='checkbox' name='del[]' value='" . $row['productCode'] . "'></td>";
echo "</tr>";
}
?>
<!-- STEP 2: Ausgabe in einer HTML-Tabelle -->
<h1>Products</h1>
<form action="index.php" method="get">
<table class="table">
<thead>
<tr>
<t>< href="?productName">Product Name</a></h>
<th><a href="?scale">Scale</></h>
<h>< href="?stock">Stock</a></t>
<t><a href="?price">Price</></h>
<h></t>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="submit" name="subDel">Submit</button>
</form>
</div>
</body>
</html>