Sunday 31 July 2011

PHP - Operators

PHP - Operators

In all programming languages, operators are used to manipulate or perform operations on variables and values. You have already seen the string concatenation operator "." in the Echo Lesson and the assignment operator "=" in pretty much every PHP example so far.

There are many operators used in PHP, so we have separated them into
the following categories to make it easier to learn them all.
  • Assignment Operators
  • Arithmetic Operators
  • Comparison Operators
  • String Operators
  • Combination Arithmetic & Assignment Operators


Assignment Operators

Assignment operators are used to set a variable equal to a value or set
a variable to another variable's value. Such an assignment of value is done with
the "=", or equal character. Example:


  • $my_var = 4;
  • $another_var = $my_var;
Now both $my_var and $another_var contain the value 4. Assignments can also be used in conjunction with arithmetic operators.

Arithmetic Operators

OperatorEnglishExample
+ Addition 2 + 4
- Subtraction 6 - 2
* Multiplication 5 * 3
/ Division 15 / 3
% Modulus 43 % 10


PHP Code:

$addition = 2 + 4; 
$subtraction = 6 - 2; 
$multiplication = 5 * 3; 
$division = 15 / 3; 
$modulus = 5 % 2; 
echo "Perform addition: 2 + 4 = ".$addition."<br />"; 
echo "Perform subtraction: 6 - 2 = ".$subtraction."<br />"; 
echo "Perform multiplication:  5 * 3 = ".$multiplication."<br />"; 
echo "Perform division: 15 / 3 = ".$division."<br />"; 
echo "Perform modulus: 5 % 2 = " . $modulus 
 . ". Modulus is the remainder after the division operation has been performed.  
 In this case it was 5 / 2, which has a remainder of 1.";

Display:

Perform addition: 2 + 4 = 6

Perform subtraction: 6 - 2 = 4


Perform multiplication: 5 * 3 = 15

Perform division: 15 / 3 = 5

Perform modulus: 5 % 2 = 1. Modulus is the remainder after the division operation has been performed.
In this case it was 5 / 2, which has a remainder of 1.

Comparison Operators

Comparisons are used to check the relationship between variables and/or
values. If you would like to see a simple example of a comparison operator in action, check out our
If Statement Lesson. Comparison
operators are used inside conditional statements and evaluate to either true
or false. Here are the most important comparison operators of PHP.



Assume: $x = 4 and $y = 5;

OperatorEnglish Example Result
== Equal To $x == $y false
!= Not Equal To $x != $y true
< Less Than $x < $y true
> Greater Than $x > $y false
<= Less Than or Equal To $x <= $y true
>= Greater Than or Equal To $x >= $y false



String Operators

As we have already seen in the Echo
Lesson
, the period "." is used to add two strings together, or more technically,
the period is the concatenation operator for strings.



PHP Code:

$a_string = "Hello";
$another_string = " Billy";
$new_string = $a_string . $another_string;
echo $new_string . "!";

Display:

Hello Billy!


Combination Arithmetic & Assignment Operators

In programming it is a very common task to have to increment a variable by some fixed amount. The
most common example of this is a counter. Say you want to increment a counter by 1, you would
have:

  • $counter = $counter + 1;
However, there is a shorthand for doing this.
  • $counter += 1;
This combination assignment/arithmetic operator would accomplish the same task. The downside to this
combination operator is that it reduces code readability to those programmers who are not used to such
an operator. Here are some examples of other common
shorthand operators. In general, "+=" and "-=" are the most widely used combination operators.

OperatorEnglish Example Equivalent Operation
+=Plus Equals $x += 2; $x = $x + 2;
-=Minus Equals $x -= 4; $x = $x - 4;
*=Multiply Equals $x *= 3; $x = $x * 3;
/=Divide Equals $x /= 2; $x = $x / 2;
%=Modulo Equals $x %= 5; $x = $x % 5;
.=Concatenate Equals $my_str.="hello"; $my_str = $my_str . "hello";

Pre/Post-Increment & Pre/Post-Decrement

This may seem a bit absurd, but there is even a shorter shorthand for the common
task of adding 1 or subtracting 1 from a variable. To add one to a variable or "increment"
use the "++" operator:
  • $x++; Which is equivalent to $x += 1; or $x = $x + 1;
To subtract 1 from a variable, or "decrement" use the "--" operator:

  • $x--; Which is equivalent to $x -= 1; or $x = $x - 1;
In addition to this "shorterhand" technique, you can specify whether you
want to increment before the line of code is being executed or after the
line has executed. Our PHP code below will display the difference.


PHP Code:

$x = 4;
echo "The value of x with post-plusplus = " . $x++;
echo "<br /> The value of x after the post-plusplus is " . $x;
$x = 4;
echo "<br />The value of x with with pre-plusplus = " . ++$x;
echo "<br /> The value of x after the pre-plusplus is " . $x;

Display:

The value of x with post-plusplus = 4

The value of x after the post-plusplus is = 5


The value of x with with pre-plusplus = 5

The value of x after the pre-plusplus is = 5
As you can see the value of $x++ is not reflected in the echoed text because
the variable is not incremented until after the line of code is executed. However,
with the pre-increment "++$x" the variable does reflect the addition immediately.

Using Comments in PHP

Comments in PHP are similar to comments that are used in HTML. The PHP comment syntax always begins with a special character sequence and all text that appears between the start of the comment and the end will be ignored.

In HTML a comment's main purpose is to serve as a note to you, the web developer or to others who may view your website's source code. However, PHP's comments are different in that they will not be displayed to your visitors. The only way to view PHP comments is to open the PHP file for editing. This makes PHP comments only useful to PHP programmers.

In case you forgot what an HTML comment looked like, see our example below.

HTML Code:

<!-- This is an HTML Comment -->


PHP Comment Syntax: Single Line Comment

While there is only one type of comment in HTML, PHP has two types. The first type we will discuss is the single line comment. The single line comment tells the interpreter to ignore everything that occurs on that line to the right of the comment. To do a single line comment type "//" or "#" and all text to the right will be ignored by PHP interpreter.

PHP Code:

<?php
echo "Hello World!"; // This will print out Hello World!
echo "<br />Psst...You can't see my PHP comments!"; // echo "nothing";
// echo "My name is Humperdinkle!";
# echo "I don't do anything either";
?>

Display:

Hello World!


Psst...You can't see my PHP comments!
Notice that a couple of our echo statements were not evaluated because we
commented them out with the single line comment.
This type of line commenting is often used for quick notes about
complex and confusing code or to temporarily remove a line of PHP code.


PHP Comment Syntax: Multiple Line Comment

Similiar to the HTML comment, the multi-line PHP comment
can be used to comment out large blocks of code or writing multiple
line comments. The multiple line PHP comment begins with " /* " and ends
with " */ ".


PHP Code:

<?php
/* This Echo statement will print out my message to the
the place in which I reside on.  In other words, the World. */
echo "Hello World!"; 
/* echo "My name is Humperdinkle!";
echo "No way! My name is Uber PHP Programmer!";
*/
?>

Display:

Hello World!

Good Commenting Practices

One of the best commenting practices that I can recommend to
new PHP programmers is....USE THEM!! So many people write complex
PHP code and are either too lazy to write good comments or believe
the commenting is not needed. However, do you really believe that you
will remember exactly what you were thinking when looking at this code
a year or more down the road?
Let the comments permeate your code and you will be a happier PHPer
in the future. Use single line comments for quick notes about a tricky
part in your code and use multiple line comments when you need to describe
something in greater depth than a simple note.

PHP Include

Without understanding much about the details of PHP, you can save yourself a great deal of time with the use of the PHP include command. include takes a file name and simply inserts that file's contents into the script that issued the include command.

Why is this a cool thing? Well, first of all, this means that you can type up a common header or menu file that you want all your web pages to include. When you add a new page to your site, instead of having to update the links on several web pages, you can simply change the Menu file.

An Include Example

Say we wanted to create a common menu file that all our pages
will use. A common practice for naming files that are to be included is to use the ".php" extension. Since we want to create a common menu
let's save it as "menu.php".

menu.php Code:

<html>
<body>
<a href="http://www.example.com/index.php">Home</a> - 
<a href="http://www.example.com/about.php">About Us</a> - 
<a href="http://www.example.com/links.php">Links</a> - 

<a href="http://www.example.com/contact.php">Contact Us</a> <br />

Save the above file as "menu.php". Now create a new file, "index.php" in the same directory as
"menu.php". Here we will take advantage of the include command to add our common menu.

index.php Code:

<?php include("menu.php"); ?>

<p>This is my home page that uses a common menu to save me time when I add
new pages to my website!</p>
</body>
</html>

Display:

Home -
About Us -

Links -
Contact Us
This is my home page that uses a common menu to save me time when I add new pages to my website!
And we would do the same thing for "about.php", "links.php", and "contact.php". Just think
how terrible it would be if you had 15 or more pages with a common menu and you decided to add
another web page to that site. You would have to go in and manually edit every single file to add this
new page, but with include files you simply have to change "menu.php" and all your problems are solved.
Avoid such troublesome occasions with a simple include file.

What do Visitors See?

If we were to use the include command to insert a menu on each of our web pages, what
would the visitor see if they viewed the source of "index.php"? Well, because the include command
is pretty much the same as copying and pasting, the visitors would see:

View Source of index.php to a Visitor:

<html>

<body>
<a href="index.php">Home</a> - 
<a href="about.php">About Us</a> - 
<a href="links.php">Links</a> - 

<a href="contact.php">Contact Us</a> <br />
<p>This is my home page that uses a common menu to save me time when I add
new pages to my website!</p>
</body>
</html>

The visitor would actually see all the HTML code as one long line of HTML code, because
we have not inserted any new line characters. We did some formatting above to make it easier to read. We will be discussing new line characters later.

Include Recap

The include command simply takes all the text that exists in the specified file and copies
it into the file that uses the include command. Include is quite useful when you want to include the same PHP, HTML, or text segment on multiple pages of a website. The include command is used widely by PHP web developers. Like PHP Echo, include is not a function, but a language construct.

The next lesson will talk about a slight variation of the include command: require. It is often best to use the require command instead of the include command in your PHP Code. Read the next lesson to find out why!

PHP Require

Just like the previous lesson, the require command is used to include a file into your PHP code. However there is one huge difference between the two commands, though it might not seem that big of a deal.

Require vs Include

When you include a file with the include command and PHP cannot
find it you will see an error message like the following:

PHP Code:

<?php
include("noFileExistsHere.php");
echo "Hello World!";
?>

Display:

Warning: main(noFileExistsHere.php): failed to open stream: No such file or directory in /home/websiteName/FolderName/tizagScript.php on line 2
Warning: main(): Failed opening 'noFileExistsHere.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/websiteName/FolderName/tizagScript.php on line 2



Hello World!

Notice that our echo statement is still executed, this is because a Warning does not prevent our PHP script from running.
On the other hand, if we did the same example but used the require statement we would get something like the following example.

PHP Code:

<?php
require("noFileExistsHere.php");
echo "Hello World!";
?>

Display:

Warning: main(noFileExistsHere.php): failed to open stream: No such file or directory in /home/websiteName/FolderName/tizagScript.php on line 2


Fatal error: main(): Failed opening required 'noFileExistsHere.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/websiteName/FolderName/tizagScript.php on line 2

The echo statement was not executed because our script execution died after the require command returned a fatal error! We recommend that you use require instead of include because your scripts should not be executing if necessary files are missing or misnamed.

No comments:

Post a Comment

VMware Cloud Learning Video's

Here is a nice summary list of all VMworld US 2018 Breakout session with the respective video playback & download URLs. Enjoy! Bra...