Introduction To Character Strings

Introduction To Character Strings
Before we start manipulating character strings with PHP, we should discuss what a character string is. A character string is a series of characters and these characters can be letters, numbers and punctuation. That's easy enough, but there are a few things to keep in mind when working with character strings and PHP.

When you store a character string in a variable, you will enclose the character string within double or single quotation marks. When you place a character string between quotation marks, you are telling the program where the character string begins and ends. The first quotation mark begins the character string and when the program encounters a second quotation mark, it knows to end the string. For example, these two lines of code are basically the same.

$string = "Gone With The Wind";

$string = 'Gone With The Wind';

Because the program ends a character string when it encounters the second quotation mark, it's a bit tricky to use quotation marks as part of the character string. If you need to use double quotation marks as part of the character string itself, you will use single quotation marks to enclose the complete string. In the example below, the double quotation marks are placed around the word old and the single quotation marks enclose the entire string. The reverse is also possible.

$string = 'Gone With The Wind is an "old" book';

You have a second option for using quotation marks within a character string. If you must use double quotation marks both to enclose the character string and within the string, you must escape the second (inside) quotation marks with a backslash \. This backslash tells the program to ignore the escaped quotation marks. The reverse is also possible.

$string = "Gond With The Wind is an \"old\" book";

Numbers are treated in a special way in most programming languages including PHP. When you work with numbers, you initially think of mathematics and you can perform many types of calculations on numbers using PHP. But when you use a number as part of a character string, you must think of that number as not a number. When numbers are part of a character string or used as a character in any way, the number is considered to be a character just like a letter. Just as you cannot add oranges and apples together, you cannot add two characters together. Just remember that you cannot perform calculations on characters even if they "look like" numbers.






This site needs an editor - click to learn more!



RSS
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map





Content copyright © 2023 by Diane Cipollo. All rights reserved.
This content was written by Diane Cipollo. If you wish to use this content in any manner, you need written permission. Contact BellaOnline Administration for details.