PHP Tutorials 7: String and Logical Operators

Welcome to the PHP tutorials: PHP Operators 3. Previously we’ve learned about some operators such as Comparison and Increment/Decrement Operators and Arithmetic and Assigment Operators. In this tutorial you will learn about the syntax and usages of String and  Logical operators.

String Operators:

There are two string operators only. They are used to join texts or a series of texts (string) together with easy syntax and usages.

  1. Concatenation (.): Brings two strings together.
    Use this operator to join two words or strings and print them out or do something else.

    Concentrate on the example below, $txt1 and $txt2 are brought together with concatenation operator and printed out.

    The Output is :     Hello world!
  2. Concatenation assignment (.=): This operator is used to append a string value of a variable to another string variable. A simple description could be like this: You can bring string values of two variables into one of the variables.

    Below example indicates the Concatenation assignment operator,  in which string values from $txt1 and $txt2 are joined and put inside variable $txt1. By appending two into one, you can echo one to print both.

    The Output is: Hello world!
Operator Name Example Result
. Concatenation $txt1.$txt2 Concatenation of $txt1 and $txt2
.= Concatenation assignment $txt1.=$txt2 Appends $txt2 to $txt1

Logical Operators:

They combine conditional statements and make it easy to play well in taking decision while working with PHP Projects. without logical operators you would write two many conditional statements with if  but these operators make it easy and you don’t need to write two many statements.

  • and (&&): joining two comparisons, and it turns true if both the comparisons are true.

Example below indicates the syntax and output from and logical operator, in which inside the if statement 100 is compared with value of $x and 50 is compared with value of $y.

Both the comparisons are true so the output is: Hello world!

  • or (||): Result true is true if either $com1 or $com2 is true, where $com1 shows a comparison like:

    and $com2 shows another process of comparing:


    Look at the example: if one of the comparison turns into true then the if statement becomes true.

    The $comp1 ($x==100) is true so the output is: Hello world!


Read the table:
Operator Name Example Result
and And $x and $y True if both $x and $y are true
&& And $x && $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
|| Or $x || $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
! Not !$x True if $x is not true

Please share your comments and question with us through comments!

Leave a Reply