Beginner php PHP 15 min read

Operators and Operands

Operators and Operands

Understanding Operators and Values in PHP

When writing PHP code, you're essentially instructing the computer to perform specific actions. A core part of these actions involves manipulating data. This is where operators come into play. Let's explore the fundamental concepts of operators and the values they work with, setting the stage for more complex calculations and logic.

Defining Named Constants

PHP allows you to create named constants, which are values that cannot be changed during the execution of your script. These constants are useful for storing values that should remain fixed, such as maximum limits or configuration settings. You create a constant using the define() function.

For instance, consider the following example:

define("MAX_PROJECTS", 99);
print MAX_PROJECTS;
print "\n";

In this code, we define a constant named MAX_PROJECTS and assign it the value 99. The print statement then displays this value. Note that when defining a constant using define(), the constant name must be enclosed in quotation marks. If you omit these quotes (e.g., define(MAX_PROJECTS, 99)), PHP will interpret the name as a reference to a previously defined constant, resulting in an error. However, when using the constant in your code, quotation marks are not required; you can simply refer to it by its name, MAX_PROJECTS.

Operators and Operands: The Building Blocks of Calculations

Operators are the symbols that perform actions on data. Think of them as the verbs in your PHP code. Common examples include the plus sign (+) for addition and the equals sign (=) for assignment. The values that an operator works with are called operands.

For example, in the expression 2 + 2, the plus sign (+) is the operator, and the numbers 2 and 2 are the operands. Similarly, in $price + $salesTax, the + operator adds the values stored in the variables $price and $salesTax.

PHP provides a wide range of operators designed to work with different data types. In this lesson, we're primarily focusing on operators for numerical data. Later on, we'll delve into operators for comparisons (e.g., determining if one value is greater than another) and logical operations (e.g., combining true/false conditions).

Arithmetic Operators for Mathematical Operations

PHP offers a set of arithmetic operators to perform common mathematical calculations. These include:

  • Addition (+): Adds two or more values together.
  • Subtraction (-): Subtracts one value from another.
  • *Multiplication ():** Multiplies two or more values.
  • Division (/): Divides one value by another.
  • Exponentiation ():** Raises a number to a specified power.
  • Modulo (%): Returns the remainder of a division.

These arithmetic operators are binary operators, meaning they require exactly two operands to function. For instance, 5 * 2 is a valid expression, but * 5 is not.

Arithmetic Operators in PHP

PHP, like most programming languages, provides a set of operators to perform mathematical calculations. These operators work with values called operands to produce a result. Let's explore the most common arithmetic operators.

Basic Arithmetic Operations

PHP supports the standard arithmetic operations you're familiar with from mathematics:

  • Addition (+): Calculates the sum of two numbers. For example, 3 + 1 results in 4.
  • Subtraction (-): Finds the difference between two numbers. 10 - 2 evaluates to 8.
  • *Multiplication (\):** Computes the product of two numbers. 2 * 3 gives you 6.
  • Division (/): Determines the quotient when one number is divided by another. 8 / 2 results in 4.
  • Modulo (%): Returns the remainder after one number is divided by another. 8 % 3 yields 2.
  • *Exponentiation (\\*): Raises a number to a specified power. 2 3 calculates 2 to the power of 3, which is 8.

Order of Operations

When an expression involves multiple operators, PHP follows a specific order of precedence to ensure consistent results. Generally, multiplication, division, and the modulo operator have higher precedence than addition and subtraction. This means those operations are performed first.

For example, in the expression 1 + 2 * 3, the multiplication 2 * 3 is evaluated first, resulting in 6. Then, the addition is performed: 1 + 6, giving a final result of 7.

You can override this default order of operations using parentheses. Parentheses force the expression within them to be evaluated first. So, (1 + 2) * 3 evaluates 1 + 2 first, resulting in 3, and then multiplies that result by 3, yielding 9.

For a comprehensive list of operator precedence in PHP, refer to the official PHP documentation: [https://www.php.net/manual/en/language.operators.precedence.php](https://www.php.net/manual/en/language.operators.precedence.php)

Combined Assignment Operators

PHP offers a convenient shorthand for combining arithmetic operations with variable assignment. The basic assignment operator (=) assigns a value to a variable. However, operators like +=, -=, *=, /=, and %= provide a more concise way to modify a variable's value based on an arithmetic calculation.

Consider a scenario where you're tracking a running total, such as the cost of items in a shopping cart. Instead of writing $total = $total + 25 to add $25 to the total, you can use the combined assignment operator: $total += 25. Similarly, $total -= 15 would subtract $15 from the current value of $total. These operators effectively perform the calculation and then assign the result back to the same variable, simplifying your code.

Combining Arithmetic Operations and Assignment

In PHP, you frequently need to perform calculations and then store the result back into a variable. PHP provides a shorthand notation called arithmetic assignment operators to simplify this process. These operators combine an arithmetic operation (like addition, subtraction, multiplication, or division) with an assignment.

For example, instead of writing $total = $total + 25, you can use the += operator and write $total += 25. This achieves the same result: adding 25 to the existing value of the $total variable and updating $total with the new sum. Similar operators exist for other arithmetic operations: -=, =, /=, and %= for subtraction, multiplication, division, and modulo, respectively. The *= operator handles exponentiation. These combined operators make your code more concise and often easier to read.

Incrementing and Decrementing Variables

PHP also provides dedicated operators for increasing (incrementing) or decreasing (decrementing) the value of a variable by one. The increment operator is ++, and the decrement operator is --. These are shortcuts for adding or subtracting 1, respectively.

So, if you have a variable $age and you want to add 1 to it, you could write $age = $age + 1 or $age += 1. However, using the increment operator, you can simply write $age++. Similarly, $age-- subtracts 1 from the value of $age. These are considered unary operators because they operate on a single variable.

Pre-increment vs. Post-increment

The position of the increment/decrement operator (before or after the variable name) affects the behavior of the operator, especially when the result of the operation is used in an expression. This difference is subtle but important.

Consider the variable $age containing the value 21.

  • Post-increment ($age++): This expression first returns the current value of $age (which is 21) and then increments the variable.
  • Pre-increment (++$age): This expression first increments the value of $age and then returns the newly incremented value.

The following code demonstrates this distinction:

<?php
$person1Age = 21;
print "Person 1 age = ";
print ++$person1Age;
print "\nPerson 1 age (after increment) = ";
print $person1Age;

$person2Age = 21;
print "\nPerson 2 age = ";
print $person2Age++;
print "\nPerson 2 age (after increment) = ";
print $person2Age;
?>

The output will be:

Person 1 age = 22
Person 1 age (after increment) = 22
Person 2 age = 21
Person 2 age (after increment) = 22

As you can see, ++$person1Age returns 22 immediately, and $person1Age remains 22. However, $person2Age++ returns 21 initially, and then $person2Age is incremented to 22. Understanding this difference is key to avoiding unexpected behavior in your PHP scripts.

That concludes our look at operators and operands. By mastering these tools, you’ll be well-equipped to write more efficient and readable PHP code.