Wednesday, 11 July 2012

PHP Strings and Operators with example tutorial


PHP - Strings
In the last lesson, PHP Echo, we used strings a bit, but didn't talk about them in depth. Throughout your PHP career you will be using strings a great deal, so it is important to have a basic understanding of PHP strings.
PHP - String Creation
Before you can use a string you have to create it! A string can be used directly in a function or it can be stored in a variable. Below we create the exact same string twice: first storing it into a variable and in the second case we place the string directly into a function.
PHP Code:
$my_string = "Tizag - Unlock your potential!";
echo "Tizag - Unlock your potential!";
echo $my_string;
In the above example the first string will be stored into the variable $my_string, while the second string will be used in the echo function and not be stored. Remember to save your strings into variables if you plan on using them more than once! Below is the output from our example code. They look identical just as we thought.
Display:
Tizag - Unlock your potential! Tizag - Unlock your potential!
PHP - String Creation Single Quotes
Thus far we have created strings using double-quotes, but it is just as correct to create a string using single-quotes, otherwise known as apostrophes.
PHP Code:
$my_string = 'Tizag - Unlock your potential!';
echo 'Tizag - Unlock your potential!';
echo $my_string;
If you want to use a single-quote within the string you have to escape the single-quote with a backslash \ . Like this: \' !
PHP Code:
echo 'Tizag - It\'s Neat!';
PHP - String Creation Double-Quotes
We have used double-quotes and will continue to use them as the primary method for forming strings. Double-quotes allow for many special escaped characters to be used that you cannot do with a single-quote string. Once again, a backslash is used to escape a character.
PHP Code:
$newline = "A newline is \n";
$return = "A carriage return is \r";
$tab = "A tab is \t";
$dollar = "A dollar sign is \$";
$doublequote = "A double-quote is \"";
Note: If you try to escape a character that doesn't need to be, such as an apostrophe, then the backslash will show up when you output the string.
These escaped characters are not very useful for outputting to a web page because HTML ignore extra white space. A tab, newline, and carriage return are all examples of extra (ignorable) white space. However, when writing to a file that may be read by human eyes these escaped characters are a valuable tool!
PHP - String Creation Heredoc
The two methods above are the traditional way to create strings in most programming languages. PHP introduces a more robust string creation tool called heredoc that lets the programmer create multi-line strings without using quotations. However, creating a string using heredoc is more difficult and can lead to problems if you do not properly code your string! Here's how to do it:
PHP Code:
$my_string = <<
Tizag.com
Webmaster Tutorials
Unlock your potential!
TEST;
echo $my_string;
There are a few very important things to remember when using heredoc.
• Use <<< and some identifier that you choose to begin the heredoc. In this example we chose TEST as our identifier.
• Repeat the identifier followed by a semicolon to end the heredoc string creation. In this example that was TEST;
• The closing sequence TEST; must occur on a line by itself and cannot be indented!
Another thing to note is that when you output this multi-line string to a web page, it will not span multiple lines because we did not have any
tags contained inside our string! Here is the output made from the code above.
Display:
Tizag.com Webmaster Tutorials Unlock your potential!
Once again, take great care in following the heredoc creation guidelines to avoid any headaches.
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
Operator
English
Example
+
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."
";
echo "Perform subtraction: 6 - 2 = ".$subtraction."
";
echo "Perform multiplication: 5 * 3 = ".$multiplication."
";
echo "Perform division: 15 / 3 = ".$division."
";
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;
Operator
English
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.
Operator
English
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 the increment to 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 "
The value of x after the post-plusplus is " . $x;
$x = 4;
echo "
The value of x with with pre-plusplus = " . ++$x;
echo "
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 by the browser.
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:

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 "//" and all text to the right will be ignored by PHP interpreter.
PHP Code:

echo "Hello World!"; // This will print out Hello World!
echo "
Psst...You can't see my PHP comments!"; // echo "nothing";
// echo "My name is Humperdinkle!";
?>
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:

/* 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.

No comments:

Post a Comment