Logical, Math and other Expressions and Operations - LEARN PHP IN A DAY: The Ultimate Crash Course to Learning the Basics of PHP in No Time (2015)

LEARN PHP IN A DAY: The Ultimate Crash Course to Learning the Basics of PHP in No Time (2015)

Chapter 3. Logical, Math and other Expressions and Operations

Introduction to Expressions and Operators

Expressions

PHP revolves around expressions. Expressions are the basic building blocks of the language and pretty much anything you write is considered an expression. A more formal definition of an expression is “anything that has a value”.

In their most basic forms, expressions are constants and variables.So for example, if you want to write$var = 42, you are essentially assigning the value of42into$var.If in some later part of your code you write$var2 = $var, you expect the value of$var2to be the same as the value of$var,42.Taking this one step further, functions (which we haven’t covered yet), are also considered expressions. A function is an expression with the value of whatever value that function returns. (Even if you are not familiar with functions inside of PHP, you should have some experience with mathematical functions. You can imagine all of this in terms ofy=f(x) and you will get an idea of what we are talking about.)

It’s easy to confuse operators with expressions in PHP, but to give you a general comparison between the two you can think of them like this. Operators are used inside of expressions. There are comparison expressions and comparison operators. The operators are the symbol that you use (i.e. >, <, ==), while the expression is what the comparison evaluates to (i.e. whether it evaluates to TRUE or FALSE).

We won’t go into more details about expressions here, as we want to keep this book more about real life applications instead of theory.

Operators

The technical definition of an operator in PHP is “something that takes one or more values (or expressions, in programming jargon) and yields another value (so that the construction itself becomes an expression)”.

Grouping of operators happens according to the number of values that the operator acts upon. There are unary operators, such as the logical NOT operator or the increments operators (!, ++, --respectively). Binary operators take two values. These are the familiar math operators that we all know (+, -, etc. ). There is also a single ternary operator that we will go into more detail when discussing logical operators.

Let’s go into analyzing the types of operators.

Operator Precedence

Operator precedence is used to determine how tightly an operator binds two expressions to one another. Operator precedence is used in cases when you want to determine the result of an expression such as1+2*4 where parentheses are not used to force precedence.

When operators have equal precedence, their associativity decides how the operators are to be grouped. For example, if we write1-2-4this will give us-5because the minus sign (-) is left-associative.

Like in regular everyday math, you can use parentheses in PHP to force the precedence of an operator. It is generally advised to use parentheses even if you have written your expression in a way so you don’t need them. Using parenthesis is a best practice that makes code more human readable and easier to understand.

Here is a comprehensive list of all operator precedence:

Associativity

Operators

More Information

Non-associative

clone new

Used to create a clone of an object or a new instance of an object respectively

Left

[

Used when reading/writing to elements of an array.

Right

**

Used for exponentiation in PHP

Right

++ -- (int) (float) (string) (array) (object) (bool) @

These are the increment and decrement operators and the type casting operators and the error control operator (more info about these later)

Right

!

Logical negation operator

Left

* / %

Arithmetic operators for multiplication, division and modulo (remainder).

Left

+ - .

Arithmetic operators for addition and subtraction as well as string concatenation.

Non-associative

== != === !== < >

Comparison operators

Left

&&

Logical AND operator

Left

||

Logical OR operator

Left

? :

Ternary operator

Right

= += -= *= **= /= .= %= &= |= ^= <<= >>=

Assignment operators

Left

and

Logical operator

Left

or

Logical operator

With that we close our discussion of operator precedence.

Arithmetic Operators

Arithmetic operators work just like the basic arithmetic operators in regular math. Let’s begin by taking a look at a list of all the arithmetic operators and then we will look at a few examples.

Example

Name

Result

-$var

Negation

Opposite (negative) of the variable.

$var + $var2

Addition

The sum of the two variables.

$var - $var2

Subtraction

The difference of the two variables.

$var * $var2

Multiplication

The product of the two variables.

$var/ $var2

Division

The quotient of the two variables

$var% $var2

Modulus

The remainder the first variable divided by the second.

$var** $var2

Exponentiation

The result obtained by raising the first variable to the power corresponding to the second variable.

When using the division operator, it is good to keep in mind that the result will be a float unless the two operands are integers that are evenly divisible. If the two operands are integers that are not evenly divisible, the returned value will be of type float.

The operands of the modulus operator are converted to integers before processing. The decimal part of the value is stripped and the remaining integer is used.

The result of the modulus operator takes its sign from the dividend.

Let’s take a look at a couple of examples.

Assignment Operators

The most basic assignment operator is “=”. You might be tempted to think of this as an “equals to”, but that would be a mistake. This operator actually means that the left operand gets the value of the expression on the right. So essentially you can think of this as “gets sets to”. With this knowledge, we can do some tricky and interesting things.

When dealing with arrays, assigning a value to a named key is done using the “=>” operator. The precedence of this operator is the same as the precedence of all assignment operators.

In addition to the basic assignment operator, there are a number of “combined operators” that come in handy when we want to use shorthand for binary arithmetic operations. Let’s say we have a variable$aequal to some value. In a later part of the code we want to set$ato be the previous value of$a plus some other value. To do that, we can write:

A simpler way of doing the above would be to use the combined operator for addition:

These combined operators work for all arithmetic operations as well as for string concatenation. Here are a few examples:

Comparison Operators

Comparison operators allow us to compare two values. Let’s take a look at a list of comparison operators.

Example

Name

Result

$var == $var2

Equal

Returns TRUE if the two variables are equal. Type juggling will be implemented if necessary.

$var === $var2

Identical

Returns TRUE if the two variables are equal and of the same type.

$var != $var2

Not equal

Returns TRUE if the two variables are not equal after type juggling.

$var <> $var2

Not equal

Returns TRUE if the two variables are not equal after type juggling.

$var!== $var2

Not identical

Returns TRUE if the two variables are not equal or they are not of the same type.

$var< $var2

Less than

Returns TRUE if the first variable is strictly less than the second.

$var> $var2

Greater than

Returns TRUE if the first variable is strictly greater than the second.

$var<= $var2

Less than or equal to

Returns TRUE if the first variable is less than or equal to the second.

$var>= $var2

Greater than or equal to

Returns TRUE if the first variable is greater than or equal to the second.

If you are comparing a string with a number or the comparison is between numerical strings, the strings are converted to numbers and the comparison is performed numerically.The type conversion is not done when using===or!== as these operators check for type as well as value.

Another conditional operator to be aware of is the ternary operator. The ternary operator is essentially a short hand for the if/else control structure (more on that later). The ternary operator has the form(some conditional expression) ? {do this if true} : {do this if false}. (The curly brackets are not used, they just there for clarity). Here is an example of a ternary operator as you would use it in an application and the corresponding if/else statement that it represents:

You can see that using the ternary operator is a lot shorter than writing out the entire if/else statement.

This concludes our overview of comparison operators. We have not extensively covered the comparison between variables of different types, but such information can be found in the PHP documentation available online so we have decided not to include it.

Error Control Operators

The error control operator is something that should be used cautiously. In PHP, the error control operator is the at sign (@). When an expression is prepended with the error control operator, any error messages associated with that expression that would normally be generated will be ignored.

Using this operator has it’s downsides because if you prepend it to an expression that generates an error that causes script termination, the script will stop without telling you why, which is bad for debugging.

We will not go into examples of using the error control operator, as you would rarely have to use it and should try to form your code so that you do not rely on it.

Incrementing and Decrementing Operators

The incrementing and decrementing operators are the ones you would see in C-style languages. These operators affect numbers and strings but not arrays and objects. Decrementing NULL values has no effect, but incrementing a NULL value results in 1.

Here is a list of the incrementing and decrementing operators.

Example

Name

Result

++$var

Pre-increment

Increments the variable by one, then returns the value.

$var++

Post-increment

Returns the value of the variable, then increments the variable by one.

--$var

Pre-decrement

Decrements the variable by one, then returns the value.

$var--

Post-decrement

Returns the value of the variable, then decrements the variable by one.

Let’s look at a few examples of how these work:

We can also increment characters. We cannot decrement characters.

Logical Operators

PHP supports logical operators that allow us to evaluate logical statements. Here is a list of logical operators

Example

Name

Result

$a and $b

And

Returns TRUE if both variables are true.

$a or $b

Or

Returns TRUE if either one of the two variables is true.

$a xor $b

Xor (either)

Returns TRUE if either one of the variables is true, but not both.

!$a

Not

Returns TRUE if he variable is not TRUE.

$a && $b

And

Returns TRUE if both variables are true.

$a || $b

Or

Returns TRUE if either one of the two variables is true.

There are two logical operators for “AND” and for “OR” because they have a different order of precedence. The most common usage of logical operators is within an if/else statement or within the first expression of a ternary operator. Let’s look at some examples of logical operators and how they are used.

String Operators

There are only two types of string operators and we have already seen both of them. The first operator is the dot operator which concatenates two strings. The second operator is the combined concatenating assignment operator which appends the argument on the right side to the argument on the left side. You will use both very frequently.

Conclusion

This concludes our overview of the different types of operators and expressions inside of PHP. You are getting closer and closer to writing your first real PHP applications! You need two more basic building blocks, covered in the next two chapters and you will be on your way to coding intermediate and advanced applications!

Exercise 1

Arithmetic-assignment operators perform an arithmetic operation on the variable at the same time as assigning a new value. For this PHP exercise, write a script to reproduce the output below. Manipulate only one variable using no simple arithmetic operators to produce the values given in the statements.

Hint: In the script each statement ends with "Value is now $variable."

Value is now 8.

Add 2. Value is now 10.

Subtract 4. Value is now 6.

Multiply by 5. Value is now 30.

Divide by 3. Value is now 10.

Increment value by one. Value is now 11.

Decrement value by one. Value is now 10.

Exercise 2

For this PHP exercise, write a script using the following variable:

$around="around";

Single quotes and double quotes don't work the same way in PHP. Using single quotes (' ') and the concatenation operator, echo the following to the browser, using the variable you created:

What goes around comes around.

Exercise 3

PHP allows several different types of variables. For this PHP exercise, you will create one variable and assign it different values, then test its type for each value.

Write a script using one variable “$whatsit” to print the following to the browser. Your echo statements may include no words except “Value is”. In other words, use the function that will output the variable type to get the requested text. Use simple HTML to print each statement on its own line and add a relevant title to your page. Include line breaks in your code to produce clean, readable HTML.

Value is string.

Value is double.

Value is boolean.

Value is integer.

Value is NULL.