0% found this document useful (0 votes)
13 views

3. PHP Operators

Uploaded by

imsisia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

3. PHP Operators

Uploaded by

imsisia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

BASIC PHP TRAINING NOTES

Outline

− Arithmetic operators
− Assignment operators
− Comparison operators
− Logical operators

PHP Operators

In PHP, operators are used to perform operations on variables and values. There are several types
of operators, each with specific purposes and use cases. This section covers the most commonly
used operators: arithmetic, assignment, comparison, and logical.

1. Arithmetic Operators

Arithmetic operators are used to perform mathematical operations on numeric values.

Operator Description Example


+ Addition $x + $y
- Subtraction $x - $y
* Multiplication $x * $y
/ Division $x / $y
% Modulus (remainder) $x % $y
** Exponentiation (power) $x ** $y

Example

$x = 10;
$y = 3;

echo $x + $y; // 13
echo $x - $y; // 7
echo $x * $y; // 30
echo $x / $y; // 3.33
echo $x % $y; // 1
echo $x ** $y; // 1000 (10^3)

2. Assignment Operators

BASICS OF PHP – NOVEMBER 2024 SOMATECH IT


Assignment operators are used in PHP to assign values to variables. The most basic assignment
operator is the equal sign (=), which assigns the value on the right to the variable on the left. In
addition to the basic assignment, PHP has several compound assignment operators that allow you
to combine assignment with arithmetic and other operations.

Operator Description Example Equivalent To


= Assign $x = $y $x = $y
+= Add and assign $x += $y $x = $x + $y
-= Subtract and assign $x -= $y $x = $x - $y
*= Multiply and assign $x *= $y $x = $x * $y
/= Divide and assign $x /= $y $x = $x / $y
%= Modulus and assign $x %= $y $x = $x % $y

i. Basic Assignment (=)

The simplest assignment operator, =, is used to assign a value to a variable.

Example:

$x = 10; // Assigns the value 10 to variable $x

ii. Compound Assignment Operators

a) Addition Assignment (+=)

Adds a value to the current value of a variable.

Example:

$x = 10;
$x += 5; // Equivalent to $x = $x + 5
echo $x; // Output: 15

b) Subtraction Assignment (-=)

Subtracts a value from the current value of a variable.

Example:

$x = 10;
$x -= 3; // Equivalent to $x = $x - 3
echo $x; // Output: 7

BASICS OF PHP – NOVEMBER 2024 SOMATECH IT


c) Multiplication Assignment (*=)

Multiplies the current value of a variable by a specified value.

Example:

$x = 10;
$x *= 2; // Equivalent to $x = $x * 2
echo $x; // Output: 20

d) Division Assignment (/=)

Divides the current value of a variable by a specified value.

Example:

$x = 10;
$x /= 2; // Equivalent to $x = $x / 2
echo $x; // Output: 5

e) Modulus Assignment (%=)

Calculates the remainder of the current value of a variable divided by a specified value.

Example:

$x = 10;
$x %= 3; // Equivalent to $x = $x % 3
echo $x; // Output: 1

iii. String Concatenation Assignment (.=)

Concatenates a string to the end of the current value of a variable.

Example:

$text = "Hello";
$text .= " World!"; // Equivalent to $text = $text . "
World!"
echo $text; // Output: Hello World!

Real-world Applications of Assignment Operators


BASICS OF PHP – NOVEMBER 2024 SOMATECH IT
1. Counting or Summing Values - In applications like shopping carts, you might add prices
to a total variable using +=.
2. Building Strings Dynamically - Use .=, especially when combining user input or
displaying multiple items.
3. Mathematical Calculations - Compound operators like *=, /=, or -= simplify code for
calculations like percentage adjustments or cumulative updates.

Assignment operators make it easy to perform updates on variables with minimal code, simplifying
processes that involve cumulative data, mathematical updates, and string concatenation.

3. Comparison Operators

Comparison operators are used to compare two values, returning a Boolean value (true or
false) based on the outcome. These are often used in conditional statements.

Operator Description Example


== Equal to $x == $y
=== Identical (equal and same type) $x === $y
!= Not equal $x != $y
<> Not equal $x <> $y
!== Not identical $x !== $y
> Greater than $x > $y
< Less than $x < $y
>= Greater than or equal to $x >= $y
<= Less than or equal to $x <= $y

Example

$x = 10;
$y = "10";

echo $x == $y; // true (equal value)


echo $x === $y; // false (not identical type)
echo $x != $y; // false (equal value)
echo $x !== $y; // true (different type)
echo $x > 5; // true
echo $x < 20; // true

4. Logical Operators in PHP

BASICS OF PHP – NOVEMBER 2024 SOMATECH IT


Logical operators allow you to combine multiple conditions and return a Boolean value (true or
false) based on the results of those combined conditions. They are especially useful in control
structures like if statements to make decisions based on multiple conditions.

Operator Description Example

&& And - Returns true if both conditions are true $x && $y

|| Or - Returns true if any of the conditions are true $x || $y

! Not - Returns true if the condition is false !$x

Examples and Explanation

i. And (&&)

• The && operator returns true only if both conditions are true. If either one or both
are false, the result is false.

$age = 25;
$hasPermission = true;

// Check if the person is above 18 AND has permission


if ($age > 18 && $hasPermission) {
echo "Access granted.";
} else {
echo "Access denied.";
}
// Output: Access granted.

ii. Or (||)

• The || operator returns true if at least one of the conditions is true. It only returns
false if both conditions are false.

$isStudent = false;
$isMember = true;

// Check if the person is a student OR a member


if ($isStudent || $isMember) {
echo "Discount applied.";
} else {
echo "No discount available.";
}
// Output: Discount applied.

BASICS OF PHP – NOVEMBER 2024 SOMATECH IT


iii. Not (!)

• The ! operator inverts the result of a condition, returning true if the condition is
false and false if the condition is true.

$isLoggedIn = false;

// Check if the person is NOT logged in


if (!$isLoggedIn) {
echo "Please log in to continue.";
}
// Output: Please log in to continue.

Real-world Applications of Logical Operators

Logical operators are essential in making complex decisions within code, such as:

• User Authentication: Check if a user has both valid credentials (&&) and required
permissions to access specific sections.
• Form Validation: Ensure multiple form fields meet the required criteria (&&) or give
options if one of several fields can be accepted (||).
• E-commerce: Apply discounts or membership benefits to a customer if they meet certain
criteria, like being a returning customer or a premium member (||).

5. Conditional (Ternary) Operator in PHP

The conditional (or ternary) operator in PHP provides a shorthand way to write simple if-
else statements. It allows you to make quick decisions within a single line of code, which can
be useful for assigning values based on conditions.

The syntax for the conditional operator is as follows:

condition ? value_if_true : value_if_false;

• condition: This is the condition being evaluated.


• value_if_true: This value is returned or executed if the condition is true.
• value_if_false: This value is returned or executed if the condition is false.

Example

Suppose you want to determine if a user is an adult based on their age:

$age = 20;

BASICS OF PHP – NOVEMBER 2024 SOMATECH IT


// Check if the age is 18 or above
$isAdult = ($age >= 18) ? "Yes" : "No";

echo "Is the user an adult? " . $isAdult;


// Output: Is the user an adult? Yes

In this example, if $age is 18 or greater, $isAdult will be set to "Yes". Otherwise, it will be
set to "No".

Real-World Applications of the Conditional Operator

The ternary operator is useful for simplifying if-else statements when only one condition is
checked, such as:

1. Form Validation: Checking if form fields have values and assigning defaults if they are
empty.
2. User Role Display: Displaying different information based on user roles, e.g., admin vs.
standard user.
3. Discount Application: Applying discounts based on user status or purchase amount.

Nested Ternary Operator

Sometimes, you may need to evaluate multiple conditions. You can nest ternary operators, but
this should be done sparingly as it can reduce readability.

$score = 85;

$grade = ($score >= 90) ? "A" :


(($score >= 80) ? "B" :
(($score >= 70) ? "C" : "F"));

echo "Grade: " . $grade;


// Output: Grade: B

In this case:

• If $score is 90 or above, the grade is "A".


• If $score is 80 or above but less than 90, the grade is "B".
• If $score is 70 or above but less than 80, the grade is "C".
• Otherwise, the grade is "F".

The conditional operator is very helpful for straightforward assignments and decisions, and it can
keep your code concise and efficient when used appropriately.

BASICS OF PHP – NOVEMBER 2024 SOMATECH IT

You might also like