Thursday, October 03, 2024

Introduction to PHP Operators, Everything You Need to Know to Get Started

Operators are symbols that represent specific actions we want to perform on data in our program. Think of them as small commands that tell the computer exactly what to do with the values, we give it. Without operators, our code would just be a bunch of words without any meaning. Operators are symbols or keywords that perform specific operations on variables and values within programming languages, including PHP .They are fundamental to programming as they enable data manipulation, decision-making, and control flow. In essence, operators allow programs to perform functional tasks using data. They serve as a bridge between data and the desired operations on that data. Therefore, understanding operators is crucial for writing efficient and readable PHP code. By understanding and utilizing operators, you can express complex programming ideas in a straightforward manner, optimize your code, and more easily troubleshoot errors. As they are the building blocks of any program, a solid grasp of operators is essential for every programmer.

A software engineer is considering which PHP operators to use in her project

A software engineer is considering which PHP operators to use in her project

In the PHP programming language, operators represent key elements that allow data manipulation and execution of various operations. PHP supports a wide range of operators and they are dividing into the following categories:
  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Increment/Decrement operators
  • Logical operators
  • String operators
  • Array operators
  • Conditional assignment operators
You may be curious about the availability of other operators, such as those in C# programming language. While bitwise operators, for instance, are more prevalent in system-level programming, game development, and cryptography, where low-level data manipulation is essential, they can also be employed in PHP to perform efficient binary operations. Nonetheless, their usage is less frequent and not recommended for novice PHP developers. Regarding error control operators, type operators, and execution operators, we will delve into these topics in future discussions. For now, it's important to familiarize yourself with the categories listed above. We'll cover them in detail in the following this lesion.

PHP Operators in Action: Practical Examples and Detailed Explanations

Rather than developing individual web pages for each PHP operator category, we will consolidate this information into a single PHP page within our php_tutorial project. This page will serve as a comprehensive resource for our clients, providing explanations and examples for all operator types. For developers, the process of creating this page will be more engaging. To begin, initiate your Apache Server and Visual Studio Code by executing the following commands in your terminal.

manuel@manuel-virtual-machine:~$ sudo apt-get update

manuel@manuel-virtual-machine:~$ sudo apt-get upgrade

manuel@manuel-virtual-machine:~$ clear

manuel@manuel-virtual-machine:~$ cd /opt/lampp

manuel@manuel-virtual-machine:~$ ls

manuel@manuel-virtual-machine:/opt/lampp$ sudo ./manager-linux-x64.run

When the XAMPP manager window opens, start the Apache Web Server and open Visual Studio Code. Click on index.php, then in the code editor panel, modify the following part of the code.

<ul>

    <li><a href="lessons/lesson01.php">

        Lesson 1. - The text printing and comments

    </a></li>

    <li><a href="lessons/lesson02.php">

        Lesson 2. - Variables and data types  

    </a></li>

    <li><a href="lessons/lesson03.php">

        Lesson 3. – Operators   

    </a></li>

</ul>

In the lesson’s directory, create a new file and name it lesson03.php. First, concentrate on the following image that explains to us what we want to explain to visitors on our site.

Categories of operators in the PHP programming language
Categories of operators in the PHP programming language

To make our PHP operators webpage easier to navigate, we'll start by providing a comprehensive list of all categories. We'll then use HTML anchors to allow users to jump directly to the specific operator they're interested in. If you need a quick reminder on how to create HTML anchors, check out this resource, here. And type the following code:

<?php

    $title = 'Lesson 3';

    require_once '../includes/header.php';

 

?>

 

<h2 class="bg-primary text-light text-center py-3">

    Operators

</h2>

 

<div class="container">

 

    <h2>PHP supports a wide range of operators and they are dividing into the following categories:</h2><br/>

   

    <ul>

        <li><a href="#arithmetic">Arithmetic operators</a></li>

        <li><a href="#assignment">Assignment operators</a></li>

        <li><a href="#comparison">Comparison operators</a></li>

        <li><a href="#increment_decrement">Increment/Decrement operators</a></li>

        <li><a href="#logical">Logical operators</a></li>

        <li><a href="#string">String operators</a></li>

        <li><a href="#array">Array operators</a></li>

        <li><a href="#conditional">Conditional assignment operators</a></li>

 

    </ul>

 

    <h2 id="arithmetic">Arithmetic operators</h2>

    <p>Arithmetic operators allow you to perform basic mathematical operations like addition, subtraction, multiplication, and division.</p>

 

    <h2 id="assignment">Assignment operators</h2>

    <p>Assignment operators are used to assign values to variables. The most common is the <code>=</code> operator.</p>

 

    <h2 id="comparison">Comparison operators</h2>

    <p>Comparison operators are used to compare two values and return true or false based on the comparison.</p>

 

    <h2 id="increment_decrement">Increment/Decrement operators</h2>

    <p>Increment and decrement operators are used to increase or decrease the value of a variable by 1.</p>

 

    <h2 id="logical">Logical operators</h2>

    <p>Logical operators are used to combine conditional statements. The most common logical operators are <code>AND</code>, <code>OR</code>, and <code>NOT</code>.</p>

 

    <h2 id="string">String operators</h2>

    <p>String operators are used to manipulate strings. The concatenation operator (<code>.</code>) is the most common.</p>

 

    <h2 id="array">Array operators</h2>

    <p>Array operators are used to compare arrays or combine them in different ways.</p>

 

    <h2 id="conditional">Conditional assignment operators</h2>

    <p>Conditional assignment operators are used to assign a value to a variable based on a condition, such as the ternary operator (<code>?:</code>).</p>

 

    </br></br></br></br></br>

 

</div>

<!-- footer -->

<?php require_once '../includes/footer.php'; ?>

As demonstrated in the preceding code, through careful planning, organization, and a creative approach, we've successfully constructed the fundamental framework for our webpage. This page will serve as a platform for in-depth explorations of various operators, accompanied by illustrative examples. To visualize the current output, simply execute our project and navigate to the Operators link. The resulting page should closely resemble the image below:

Web page in the first stage of development, with excellent work organization

Web page in the first stage of development, with excellent work organization

We can now devote our attention to each individual category of PHP operators. For each category, we will create a corresponding code example and integrate it into the appropriate section of our webpage.

Arithmetic Operators - These operators allow basic mathematical operations:

addition +

subtraction -

multiplication *

division /

remainder of division %

Insert the following PHP code for arithmetic operators

       <?php

        // Defining variables

        $number1 = 67;

        $number2 = 8;

 

        // Addition

        $sum = $number1 + $number2;

        echo "<p>The sum of numbers $number1 and $number2 is: $sum</p>";

 

        // Subtraction

        $difference = $number1 - $number2;

        echo "<p>The difference between numbers $number1 and $number2 is: $difference</p>";

 

        // Multiplication

        $product = $number1 * $number2;

        echo "<p>The product of numbers $number1 and $number2 is: $product</p>";

 

        // Division

        $quotient = $number1 / $number2;

        echo "<p>The quotient of numbers $number1 and $number2 is: $quotient</p>";

 

        // Modulus (remainder of division)

        $remainder = $number1 % $number2;

        echo "<p>The remainder when dividing $number1 by $number2 is: $remainder</p>";

    ?>

Assignment OperatorsAssignment operators are used to assign values to variables: 

simple assignment =

add and assign +=

subtract and assign -=

multiply and assign *=

divide and assign /=

modulo and assign %=

 Insert the following PHP code for assignment operators

  <?php

    // Defining variables

        $number1 = 67;

        $number2 = 8;

        $number3 = 67;

 

    // Addition and assignment

        $number3 += $number2;

        echo "<p>$number1 += $number2; Equivalent to $number3 = $number1 + $number2; The sum of numbers is: $number3</p>";

 

        // Subtraction and assignment

        $number3 = 67;

        $number3 -= $number2;

        echo "<p>$number1 -= $number2; Equivalent to $number3 = $number1 - $number2; The difference between numbers is: $number3</p>";

 

        // Multiplication and assignment

        $number3 = 67;

        $number3 *= $number2;

        echo "<p>$number1 *= $number2; Equivalent to $number3 = $number1 * $number2; The product of numbers is: $number3</p>";

 

        // Division and assignment

        $number3 = 67;

        $number3 /= $number2;

        echo "<p>$number1 /= $number2; Equivalent to $number3 = $number1 / $number2; The quotient of numbers is: $number3</p>";

 

        // Modulus and assignment

        $number3 = 67;

        $number3 %= $number2;

        echo "<p>$number1 %= $number2; Equivalent to $number3 = $number1 % $number2; The remainder when dividing is: $number3</p>";  

?>

Comparison Operators - Comparison operators are used to compare two values, resulting in either true or false: 

equal to ==

not equal to !=

greater than >

less than <

greater than or equal to >=

less than or equal to <=

Insert the following PHP code for comparison operators:

    <?php

        // Defining variables

        $number1 = 67;

        $number2 = 8;

 

        // Printing results using ternary operator

        echo "<p>Operator == ... Number $number1 is " . ($number1 == $number2 ? "equal to" : "not equal to") . " number $number2.</p>";

        echo "<p>Operator != ... Number $number1 is " . ($number1 != $number2 ? "not equal to" : "equal to") . " number $number2.</p>";

        echo "<p>Operator >  ... Number $number1 is " . ($number1 > $number2 ? "greater than" : "not greater than") . " number $number2.</p>";

        echo "<p>Operator <  ... Number $number1 is " . ($number1 < $number2 ? "less than" : "not less than") . " number $number2.</p>";

        echo "<p>Operator >= ... Number $number1 is " . ($number1 >= $number2 ? "greater than or equal to" : "not greater than or equal to") . " number $number2.</p>";

        echo "<p>Operator <= ... Number $number1 is " . ($number1 <= $number2 ? "less than or equal to" : "not less than or equal to") . " number $number2.</p>";

    ?>

Increment/Decrement Operators Increment and decrement operators allow increasing or decreasing the value of a variable by 1:

increment ++

decrement –

 Insert the following PHP code for increment and decrement operators: 

<?php

        // Increment operator (++)

        $x = 67;

        echo "<p>x = 67 ... x before increment: " . $x . "</p>";

 

        // Pre-increment

        $y = ++$x;

        echo "<p>y = ++x ... x after pre-increment: " . $x . "</p>";

        echo "<p>y: " . $y . "</p>";

 

        // Post-increment

        $z = $x++;

        echo "<p>z = x++ ... x after post-increment: " . $x . "</p>";

        echo "<p>z: " . $z . "</p>";

 

        // Decrement operator (--)

        $a = 8;

        echo "<p>a = 8 ... a before decrement: " . $a . "</p>";

 

        // Pre-decrement

        $b = --$a;

        echo "<p>b = --a ... a after pre-decrement: " . $a . "</p>";

        echo "<p>b: " . $b . "</p>";

 

        // Post-decrement

        $c = $a--;

        echo "<p>c = a-- ... a after post-decrement: " . $a . "</p>";

        echo "<p>c: " . $c . "</p>";

    ?>

Logical Operators - Logical operators allow combining multiple conditions:

logical AND &&

logical OR ||

logical NOT !

 Insert the following PHP code for logical operators

    <?php

        // Logical AND (&&) operator

        $x = 5;

        $y = 10;

        echo "<p>Logical AND (&&) operator ... x = 5, y = 10 ... x > 0 && y > 0 ... Both x and y are positive. " . ($x > 0 && $y > 0 ? "True" : "False") . "</p>";

 

        // Logical OR (||) operator

        $x = 5;

        $y = -10;

        echo "<p>Logical OR (||) operator ... x = 5, y = -10  ... x > 0 || y > 0 ... At least one of x or y is positive. " . ($x > 0 || $y > 0 ? "True" : "False") . "</p>";

 

        // Logical NOT (!) operator

        $x = 5;

        echo "<p>Logical NOT (!) operator ... x = 5, ... !x > 0 ... x is positive. " . (!$x > 0 ? "True" : "False") . "</p>";;

    ?>

String Operators - String operators allow manipulation of strings:

concatenation .

concatenate and assign .=

Insert the following PHP code for string operators

      <?php

        // Names to concatenate

        $firstName = "Manuel";

        $lastName = "Radovanović";

 

        // Concatenate the first and last name

        $fullName = $firstName . " " . $lastName;

 

        // Print the result

        echo "<p>Concatenating the strings " . $firstName . " and " . $lastName . " with concatenation . results in: " . $fullName . ".</p>";

    ?>

Array Operators - Array operators allow manipulation and comparison of arrays:

union +

equality ==

identity ===

inequality !=

non-identity !==

Insert the following PHP code for array operators:  

<?php

        // Two arrays for comparison

        $array1 = array(1, 2, 3);

        $array2 = array(4, 5, 6);

 

        // Display both arrays

        echo "<p>Array 1: ";

        print_r($array1);

        echo "</p>";

 

        echo "<p>Array 2: ";

        print_r($array2);

        echo "</p>";

 

        // Array comparison operators

        echo "<p>Array comparison operators:</p>";

 

        // Union operator (+), but using array_merge instead

        $unionArray = array_merge($array1, $array2);

        echo "<p>Array union (correct result): ";

        print_r($unionArray);

        echo "</p>";

 

        // Equality operator (==)

        $areEqual = $array1 == $array2;

        echo "<p>Are arrays equal? " . ($areEqual ? "Yes" : "No") . "</p>";

 

        // Identity operator (===)

        $areIdentical = $array1 === $array2;

        echo "<p>Are arrays identical? " . ($areIdentical ? "Yes" : "No") . "</p>";

 

        // Inequality operator (!=)

        $areNotEqual = $array1 != $array2;

        echo "<p>Are arrays different? " . ($areNotEqual ? "Yes" : "No") . "</p>";

 

        // Non-identity operator (!==)

        $areNotIdentical = $array1 !== $array2;

        echo "<p>Are arrays different by identity? " . ($areNotIdentical ? "Yes" : "No") . "</p>";

    ?>

Conditional Assignment Operators - Conditional assignment operators allow you to assign values based on conditions:

ternary operator ?:

null coalescing operator ??

 Insert the following PHP code for conditional assignment operators

   <!-- Ternary Operator (?:) -->

    <p>Ternary Operator (?:)</p>

 

    <p> $broj = 10; $result = ($number > 5) ? "Number is greater than 5" : "Number is less than or equal to 5";</p>

 

    <p>

        <?php

        $number = 10;

        $result = ($number > 5) ? "Number is greater than 5" : "Number is less than or equal to 5";

        echo "Result: " . $result

        ?>

    </p>

 

    <!-- Explanation:-->

    <p>

        The ternary operator is a shorthand way of writing if-else statements.

        In this example, we check if the variable $number is greater than 5.

        If it is, the result will be Number is greater than 5, otherwise,

        it will be Number is less than or equal to 5.

    </p>

 

    <!-- Null coalescing operator (??) -->

    <p>Null coalescing operator (??)</p>

 

    <p>$name = $_GET['name'] ?? 'Guest';</p>

 

    <p>

        <?php

        $name = $_GET['name'] ?? 'Guest';

        echo "Hello, " . $name . "!";

        ?>

    </p>

 

    <!-- Explanation: -->

    <p>

        The null coalescing operator is used to check for null values.  

        If the left side of the operator is null, the right side is assigned.  

        In this example, if the GET parameter "name" is not set, the variable `$name` will be assigned the value "Guest".  

        This operator is useful for setting default values.

    </p>


The result of coding the Operators page

The result of coding the Operators page

If you now execute the Operators page, the result will be as follows:


PHP supports a wide range of operators and they are dividing into the following categories:

Arithmetic operators

Assignment operators

Comparison operators

Increment/Decrement operators

Logical operators

String operators

Array operators


Conditional assignment operators

Arithmetic operators

Arithmetic operators allow you to perform basic mathematical operations like addition, subtraction, multiplication, and division.

The sum of numbers 67 and 8 is: 75

The difference between numbers 67 and 8 is: 59

The product of numbers 67 and 8 is: 536

The quotient of numbers 67 and 8 is: 8.375

The remainder when dividing 67 by 8 is: 3


Assignment operators

Assignment operators are used to assign values to variables. The most common is the = operator.

67 += 8; Equivalent to 75 = 67 + 8; The sum of numbers is: 75

67 -= 8; Equivalent to 59 = 67 - 8; The difference between numbers is: 59

67 *= 8; Equivalent to 536 = 67 * 8; The product of numbers is: 536

67 /= 8; Equivalent to 8.375 = 67 / 8; The quotient of numbers is: 8.375

67 %= 8; Equivalent to 3 = 67 % 8; The remainder when dividing is: 3


Comparison operators

Comparison operators are used to compare two values and return true or false based on the comparison.

Operator == ... Number 67 is not equal to number 8.

Operator != ... Number 67 is not equal to number 8.

Operator > ... Number 67 is greater than number 8.

Operator < ... Number 67 is not less than number 8.

Operator >= ... Number 67 is greater than or equal to number 8.

Operator <= ... Number 67 is not less than or equal to number 8.


Increment/Decrement operators

Increment and decrement operators are used to increase or decrease the value of a variable by 1.

x = 67 ... x before increment: 67

y = ++x ... x after pre-increment: 68

y: 68

z = x++ ... x after post-increment: 69

z: 68

a = 8 ... a before decrement: 8

b = --a ... a after pre-decrement: 7

b: 7

c = a-- ... a after post-decrement: 6

c: 7

 

Logical operators

Logical operators are used to combine conditional statements. The most common logical operators are AND, OR, and NOT.

Logical AND (&&) operator ... x = 5, y = 10 ... x > 0 && y > 0 ... Both x and y are positive. True

Logical OR (||) operator ... x = 5, y = -10 ... x > 0 || y > 0 ... At least one of x or y is positive. True

Logical NOT (!) operator ... x = 5, ... !x > 0 ... x is positive. False


String operators

String operators are used to manipulate strings. The concatenation operator (.) is the most common.

Concatenating the strings Manuel and Radovanović with concatenation . results in: Manuel Radovanović.


Array operators

Array operators are used to compare arrays or combine them in different ways.

Array 1: Array ( [0] => 1 [1] => 2 [2] => 3 )

Array 2: Array ( [0] => 4 [1] => 5 [2] => 6 )

Array comparison operators:

Array union (correct result): Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )

Are arrays equal? No

Are arrays identical? No

Are arrays different? Yes

Are arrays different by identity? Yes

 

Conditional assignment operators

Conditional assignment operators are used to assign a value to a variable based on a condition, such as the ternary operator (?:).

Ternary Operator (?:)

$number = 10; $result = ($number > 5) ? "Number is greater than 5" : "Number is less than or equal to 5";

Result: Number is greater than 5

The ternary operator is a shorthand way of writing if-else statements. In this example, we check if the variable $number is greater than 5. If it is, the result will be Number is greater than 5, otherwise, it will be Number is less than or equal to 5.

Null coalescing operator (??)

$name = $_GET['name'] ?? 'Guest';

 Hello, Guest!

The null coalescing operator is used to check for null values. If the left side of the operator is null, the right side is assigned. In this example, if the GET parameter "name" is not set, the variable `$name` will be assigned the value "Guest". This operator is useful for setting default values.


You can also watch the creation of the entire Operators page in the following video.


PHP - 3. Introduction Basic Operators



 

 

 

 

 

 

 

No comments:

Post a Comment