PHP – Lesson 03: Data Types – Strings

In This Lesson:


Strings, strings, and more strings

What is a string?

A string is a series of single characters that carry a text value. That means that you could say “There are 20000 leagues under the sea,” and PHP would read “20000” as a line of text (or a string) instead of a number (or integer). There is no practical limit on the length of a string.

Displaying strings

There are two main functions we will use to get started in displaying strings (or an data types for that matter!) in our browsers:

  • echo
  • print

These essentially do the exact same thing, but echo can take multiple parameters and is a little bit faster since it doesn’t have to return a value the way that print does.

An example of using either one:

  • echo "I like cookies.";
  • print "I like cookies.";

Both of these output the following to the screen: I like cookies.

You can also echo variables that hold string data type values….

$my_favorite = "I like cookies.";
echo $my_favorite;

This will output to the browser: I like cookies.

Notice in the above example that the textual string has quotes around it, whereas $my_favorite does not. Although we COULD put quotes around the variable, we don’t have to because the value of the entire string is already stored inside of it AS A STRING.

We can also state a variable inside of a string, like this:

$my_favorite = "I like cookies.";
echo "$my_favorite I also like ice cream.";

This will output to the browser: I like cookies. I also like ice cream.

That brings up another point: it is a good practice to put curly braces around a variable in a double-quoted string so that the variable is clearly delineated from the rest of the string, like this:

echo "{$my_favorite} I also like ice cream.";

This does two main things:

  1. it visually separates the variable from the rest of the double-quoted string for the programmer
  2. it allows us to run a variable right up next to a double-quoted  string value without using white space in between characters

A better example of why curly braces are important around variables in double-quoted strings is below. In this example, let’s say that the value of $gender in this instance is set to “male“:

$gender = "male";

Now, let’s assume that the page will be using the variable in both singular/adjective and plural form. See how the arguments below would produce different results:

echo "The individual in the study is $gender.<br>";
echo "There were 26 $genders in this study.";

vs.

echo "The individual in the study is {$gender}.<br>";
echo "There were 26 {$gender}s in this study.";

In the first example, $gender would be read properly, but its second line using $genders would NOT work because a variable called $genders was never declared and doesn’t exist. The second example, however, would parse the information correctly to produce the following output:

The individual in the study is male.
There were 26 males in this study.

Concatenation or “full-stop”

Another way to link strings together is with a full-stop, or the concatenation period. Here’s an example:

$imgFolder = "images/";
$thumbs = "thumbs/";
$fullSize = "large/";
$filename = "bullet.jpg";
//Later in the page's html...
<img src="<?php echo $imgFolder.$thumbs.$filename; ?>" alt="">

The above script would produce the following html code:
<img src="images/thumbs/bullet.jpg" alt="" >

Thus, it would print an image out to the screen using the concatenated path to the file.

Let’s also look at another example:

$eat = "I like to eat";
$food = "hot dogs.";
echo $eat." ".$food;

This returns: I like to eat hot dogs.

The full-stop after $eat indicates that PHP should add the next part in quotes, a “space”, and then another full-stop tells PHP to tack $food on the end of it all. Without the  ." ". code, $eat and $food would be run together without a space in between, resulting in “I like to eathot dogs.

For a working example file with comments, download the full-stop.php testing file and load it into your web serving development folder.


Using Quotes

Do I use single or double quotes?

Here’s a basic difference to start us off:

  • Single quotes treat anything inside of them as literal text. This includes variable $, backslash \, and curly brace {} symbols. They will be read as text characters only.
  • Double quotes can hold strings like single quotes, but they will continue to allow the PHP engine to process variables and special characters when the engine comes across them.

Here is an illustration of the difference defined above:

$name = 'Marcus';
//Single quotes below treat $name as literal text
echo 'My name is {$name}.';

The browser will return: My name is {$name}.

$name = 'Marcus';
//Double quotes below treat $name as a variable because it reads $ as a special character
echo "My name is {$name}.";

The browser will return: My name is Marcus.

Quotes within quotes

You will quickly realize that you can’t put the same kind of quotes within other sets of quotes because the PHP engine gets confused and thinks you are ending your string too soon. It will throw an error. Here’s an example of a mistake:

echo "Richard told me to watch "Saturday Night Live" on Tv."; //wrong wrong wrong!

What happens is that the PHP engine thinks the string ends at the quote marks preceding the word “Saturday Night Live” and doesn’t know what to do with the rest of the line. This will throw an error. What you need to do instead is use a backslash before the internal quotes marks to “escape” the double quote special character. As follows:

echo "Richard told me to watch \"Saturday Night Live\" on Tv."; //correct usage

The presence of a backslash inside double quotes indicates to PHP the immediate character following it is to be treated as a normal part of the text string.

Here is a basic checklist to remember with quotes:

  • Single quotes and apostrophes are fine inside of a double-quoted string.
  • Double quotes are fine inside a single-quoted string.
  • Initial single quotes treat all characters as literal text.
  • Initial double quotes will allow PHP special character directives to run (such as variables and escaping).


Some Common String Functions

Some common string functions are listed below, along with their conversion output of the following variable string assignment:

// SET EXAMPLE TESTING VARIABLES
$test
= "this IS a string.";
$test2 = " This is an example of trimming white space at start of line.";

  • Code to convert a string to all lower case:
    • echo strtolower($test);
    • this is a string.
  • Code to convert a string to all upper case:
    • echo strtoupper($test);
    • THIS IS A STRING.
  • Code to convert a string so that first word has an initial cap:
    • echo ucfirst($test);
    • This IS a string.
  • Code to convert a string to have all initial caps:
    • echo ucwords($test);
    • This Is A String.
  • Find the number count of characters in a string:
    • echo strlen($test);
    • 18
  • Find a string within a string.
    • echo strstr($test, "IS");
    • IS a string.
  • Find and replace a string pattern with a new string.
    • echo str_replace("string", "very short string", $test);
    • this is a very short string.
  • Remove whitespace (extra spaces) from the beginning or end of a string. Echoing two variables with a concatenation mark or full-stop….
    • echo $test.trim($test1);
    • this IS a string.This is an example of trimming white space at start of line.

For a lot more string functions, you can visit: http://us3.php.net/manual/en/book.strings.php.

For a working example file with comments, download the string_functions.php testing file and load it into your web serving development folder.

Strings 01 – Introduction: the echo and print commands (5:24)

For better quality, select 720p from the gear icon in the lower right video frame.
For rapid initial loading, select 360p or lower from the gear icon in the lower right video frame. You can switch it to higher resolution shortly after several seconds of loading.


Strings 02 – Using string variables and curly braces (11:35)

For better quality, select 720p from the gear icon in the lower right video frame.
For rapid initial loading, select 360p or lower from the gear icon in the lower right video frame. You can switch it to higher resolution shortly after several seconds of loading.


Strings 03 – Concatenation (14:24)

For better quality, select 720p from the gear icon in the lower right video frame.
For rapid initial loading, select 360p or lower from the gear icon in the lower right video frame. You can switch it to higher resolution shortly after several seconds of loading.


Strings 04 – Quotes (14:57)

For better quality, select 720p from the gear icon in the lower right video frame.
For rapid initial loading, select 360p or lower from the gear icon in the lower right video frame. You can switch it to higher resolution shortly after several seconds of loading.


String Functions (14:27)

For better quality, select 720p from the gear icon in the lower right video frame.
For rapid initial loading, select 360p or lower from the gear icon in the lower right video frame. You can switch it to higher resolution shortly after several seconds of loading.


Strings 04 – Quotes ()

&amp;lt;/object&amp;gt;&amp;lt;/div&amp;gt;