A sequence of characters compose a string. PHP comes equipped with an arsenal of string related functions. This posting will cover three string functions: strlen, strpos and strrpos.
Strings are enclosed in a pair of either single or double quotation marks. Characters are taken at face value when enclosed in single doubles. Additional processing occurs when characters are enclosed in double quotation marks; variable substitutions are made and escaped characters (e.g. \n) are translated into character codes.
In the example below, $firstSaying and $secondSaying have matching string values. The variable $person is automatically evaluated to ‘day’ because the value of $firstString is enclosed in double quotes.
<?php $duration = 'day'; $firstSaying = "An apple a $duration"; $secondSaying = 'An apple a day'; ?>
Internally, the value of $secondSaying is:
| Character | A | n | a | p | p | l | e | a | d | a | y | |||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Position | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
The table above the shows the position of each character within the string. Some programming languages use a starting position of one (Visual Basic) while the majority use a starting position of zero.
To retrieve a single character from a string, place the character position enclosed in brackets [ ] immediately after the string variable. For example, the following retrieves and displays 13th character in $secondString.
<?php $secondSaying = 'An apple a day'; echo($secondSaying[13]); ?>
This program outputs the character y.
PHP is lenient when attempting at get characters that falls outside boundaries of a string (e.g. retrieving characters using a negative position or beyond the length of the string. It always returns an empty string “”. Bear in mind that trying this in programming languages may get you into trouble.
String Length
The function strlen accepts one argument, a string, and returns the length of that string. Since the first character begins at position zero, the string length is one greater than last character position in the string.
<?php
$secondSaying = 'An apple a day';
//Retrieve the length of the string
$secondSayingLength = strlen($secondSaying);
echo("The length of string '$secondSaying' is $secondSayingLength.\n");
?>
Output: The length of string 'An apple a day' is 14.
Calling strlen on a null value returns a length of zero.
Searching within Strings
To locate the starting position of text with a string, use the function strpos. Standard calls to strpos accept two arguments, the first parameter being the string to search (the subject or the haystack) and second the text to find (the needle). The text can be a single character or a string consisting of multiple characters. The function will begin at the left hand side of the string and search right for the string. If the search text cannot be located, a boolean value false is returned.
Note: Be careful when checking if the search text is found. The starting position of 0 has the same value as the boolean false. Use the identical === binary operator or the not identical operator !== to make this differentiation.
<?php
$secondSaying = 'An apple a day';
$searchText = 'a';
//Find the position of 'a'
$positionOfA = strpos($secondSaying, $searchText);
if ($positionOfA !== false) {
echo("The first occurrence of '$searchText' is at position $positionOfA.\n");
}
else {
echo("Could not locate $searchText\n");
}
?>
The source code above retrieves the first occurrence of a lowercase ‘a’.
| Character | A | n | a | p | p | l | e | a | d | a | y | |||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Position | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
Output: The first occurrence of 'a' is at position 3.
But the first occurrence of the letter a is at position zero.
Well, strpos is case sensitive. It locates the first lowercase ‘a’; an uppercase ‘A’ isn’t a lowercase one. To locate the first occurrence of of ‘a’ regardless of its case use stripos. In the example above it returns the integer zero.
Case insensitive string functions ignore the case of characters when performing operations. These functions begin with stri where their case sensitive counterparts begin with str. For example, stricmp is case insensitive and strcmp is case sensitive.
The function strpos accepts an optional parameter, the position within the string (offset) to conduct a search. To find the second ‘a’ within the string, I will begin searching one character after the first ‘a’ at $positionOfA + 1.
| Character | A | n | a | p | p | l | e | a | d | a | y | |||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Position | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
I cannot assume that there will always be text following the first ‘a’ to search on. PHP doesn’t care if you search outside the boundary of the string, but in this example, I will keep my search within the string by using strlen.
<?php
$secondSaying = 'An apple a day';
$secondSayingLength = strlen($secondSaying);
$searchText = 'a';
//Find the position of 'a'
$positionOfA = strpos($secondSaying, $searchText);
$positionOfSecondA = false;
if ($positionOfA !== false) {
// Find the position of the second 'a'
if ($secondSayingLength > ($positionOfA + 1)) {
$positionOfSecondA = strpos($secondSaying, $searchText, $positionOfA + 1);
}
}
if ($positionOfSecondA !== false) {
echo("The second occurrence of '$searchText' is at position $positionOfSecondA.\n");
}
else {
echo("Could not locate second occurrence of '$searchText'.\n");
}
?>
Output: The second occurrence of 'a' is at position 9.
To find the last occurrence ‘a’, use the function strrpos. This searches for a string in reverse, hence the extra ‘r’ in the function name. It accepts the same arguments as the forward version of the search.
For those living in the dark ages of PHP 4 (waves hand), strrpos only searches on single characters. If I wanted to find the last occurrence of the word apple and pass the string ‘apple’ as an argument, strrpos would search for the last occurrence of the letter ‘a’. This will not give us the correct result in PHP 4.
Here’s an example of finding the last occurrence of the letter ‘a’ in PHP 5.
<?php
$secondSaying = 'An apple a day';
$searchText = 'a';
//Find the last position of 'a'
$positionOfA = strrpos($secondSaying, $searchText);
if ($positionOfA !== false) {
echo("The last occurrence of '$searchText' is at position $positionOfA.\n");
}
else {
echo("Could not locate the last occurrence of '$searchText'.\n");
}
?>
Output: The last occurrence of 'a' is at position 12.
There is one function and one binary operator for determining if a variable is an object.
Is_object
is_object($aVar) – Determines if $aVar is an object. When $aVar is instantiated (created) from a class, this function returns true. Otherwise it returns false.
We need an object to work with. This primitive caveman will suffice.
File: Caveman.php
<?php
class Caveman {
public function greet() {
echo("Grunt.\n");
}
}
?>
The following program tests if the variable $fred is an object.
<?php
require_once("Caveman.php");
$fred = new Caveman();
if (is_object($fred) === true) {
echo("This is an object.\n");
}
else {
echo("This is not an object.\n");
}
?>
Since $fred was created from a Caveman class, it is an object and is_object($fred) returns true. The if condition evaluates to true and the program outputs: This is an object.
Instanceof
The binary operator instanceof determines if $aVar is instantiated from a given class. One operand is the variable being tested and the other the name of a class or interface. Moreover, it also tests the following:
- Determines if $aVar inherits (extends) from a given class.
- Determines if $aVar implements a given interface.
So, if a $var was created from a given class, created from a class that extends a given class or implements a given interface instanceof evaluates to true. Otherwise it returns false.
The following example tests if $fred is created from a class named Caveman.
<?php
require_once("Caveman.php");
$fred = new Caveman();
if (($fred instanceof Caveman) === true) {
echo("This is a caveman.\n");
}
else {
echo("This is not an caveman.\n");
}
?>
Since $fred was assigned new Caveman(); the object is an instance of the Caveman class. The instanceof operator evaulates to true and the program outputs: This is a caveman.
To demonstrate the first bullet point when instanceof evaluates to true:
- Determines if $aVar inherits (extends) from a given class.
We need a second class that extends from Caveman.
File: RenaissanceMan.php
<?php
require_once("Caveman.php");
class RenaissanceMan extends Caveman {
public function greet() {
echo("Greetings, gentleman.\n");
}
}
?>
The variable $fred is tested if it is an instantiated from Caveman. Although $fred is created from the RenaissanceMan class, the RenaissanceMan class definition inherits from the Caveman class and instanceof operator evaluates to true.
<?php
require_once("RenaissanceMan.php");
$fred = new RenaissanceMan();
if (($fred instanceof Caveman) === true) {
echo("This is a caveman.\n");
}
else {
echo("This is not an caveman.\n");
}
?>
The output is This is a caveman. The boolean expression ($fred instanceof RenaissanceMan) in the example above would also evaluate to true.
Demonstrating the second bullet point:
- Determines if $aVar implements a given interface.
We need an interface, a definition that defines a behavior.
File: Talkative.php
<?php
interface Talkative {
public function greet();
}
?>
Adjust the Caveman class definition to indicate the all caveman can greet people.
File: Caveman.php
<?php
require_once("Talkative.php");
class Caveman implements Talkative {
public function greet() {
echo("Grunt.\n");
}
}
?>
The following example tests if $fred implements the Talkative interface.
<?php
require_once("RenaissanceMan.php");
$fred = new RenaissanceMan();
if (($fred instanceof Talkative) === true) {
echo("This creature is talkative.\n");
}
else {
echo("This creature is quiet.\n");
}
?>
RenaissanceMan inherits any protected and public methods, properties and interfaces that Caveman may have. Caveman implements the Talkative interface and since RenaissanceMan extends Caveman, RenaissanceMan also implements the Talkative interface. The binary instanceof operator evaluates to true and the program outputs: This creature is talkative.
The following are a list of primitive type functions that tests if a variable if of a given primitive type (boolean, integer, float, string, etc.). If the variable is of the type being tested a boolean of true is returned from the function, otherwise a false is returned.
Remember, that variables can be of different types but have the same value. For example, boolean of false has the same value as the integer zero. The function is_bool tests if an argument, a variable passed to a function, is a boolean type. An example is:
<?php
$isWalking = false;
if (is_bool($isWalking) === true) {
echo("This variable is of type boolean.\n");
}
else {
echo("This variable is not of type boolean.\n");
}
?>
Since $isWalkingis assigned a value false and false is a boolean type, the is_bool function returns true, and the program outputs: This variable is of type boolean. If I were to assign $isWalking a value of 0 which is of type integer, is_bool would return false. The program would output: This variable is not of type boolean.
Here is a list of function that tests the type of a given variable, $aVar. You can find an extensive list in the PHP manual.
Type Functions
is_bool($aVar)– Tests if $aVar is a boolean.is_null($aVar)– Tests if $aVar is of type null, a type that has no value.is_array($aVar)– Tests if $aVar is an array.is_resource($aVar)– Tests if $aVar is a resource, a connection to a file, database, web server, etc.
Numeric Type Functions
is_int($aVar)– Tests if $aVar is an integer, a positive or negative whole number including zero.is_integer($aVar)– Also tests if $aVar is an integer.is_long($aVar)– Does the same thing asis_int. In languages such as C, a long type handles large integers.is_float($aVar)– Tests if $aVar is a fractional positive or negative number, including 0.0. The value 0.0 is of type float and 0 an integer.is_double($aVar)– Does the same test asis_float.is_real($aVar)– Yes, another function that does the same thing asis_float.
String Type Functions
is_string($aVar)– Tests if $aVar is a string.is_unicode($aVar)– (PHP 6) Tests if $aVar is a unicode string. Unicode strings support an extended set of characters for foreign (non-English) languages. The buzzword for this is internationalization. At the time of this writing, I have never usedis_unicodeas PHP 6 does not exist yet.
A logical NOT inverts its input value.
Speaking in terms of logical gates (refer to the previous posting), its truth table is:
| A | NOT A |
| false | true |
| true | false |
In PHP, this is a unary logic operator, denoted by !, that prefixes its input value.
<?php
$fileName = "test.txt";
$fileHandle = @fopen($fileName, "rt");
if (!$fileHandle) {
echo("Unable to open file $fileName for reading.");
}
else {
//Do file processing here
fclose($fileHandle);
}
?>
This is a commonplace shorthand example of using a logical NOT. The function fopen attempts to open a file. Assuming that test.txt does not exist relative to where the program is running, fopen returns false and assigns the value of false to $fileHandle. In boolean expression (!$fileHandle) the value of $fileHandle is inverted to true. The expression evaluates to true and the code-block in the if-statement is run.
Output: Unable to open file test.txt for reading.
In the land of loosely typed languages, there is where things become hazy as to what exactly is being tested in an if-statement. After all, logical NOT operations apply to strictly boolean inputs and in PHP you can send any data type as an input.
<?php
$aString = "The quick brown fox jumps over the lazy dog.";
$stringLength = strlen($aString);
echo("The length of the string is $stringLength.\n");
if (!$stringLength) {
echo("The string is empty or null.");
}
else {
echo("The string has text in it.");
}
?>
The function strlen accepts a string as input and calculates the length of that string. In the above example, the string tested is 44. Well, 44 is a number and how does this apply to a logical NOT truth table? The number zero is false and any non-zero number is interpreted as true. So, (!$stringLength) is (!44) which is (!true). Inverting true gives us (false) and the expression evaluates to false, the code-block immediately after the condition is not executed and the else code-block is run.
Output:
The length of the string is 44.
The string has text in it.
Here is an example of an array being passed as an input to a logical NOT.
<?php
$anArray = array('first_name' => 'Paul');
if (!$anArray) {
echo("The array is empty or null.");
}
else {
echo("The array has information in it.");
}
?>
PHP interprets a non-empty array as a true value. The condition (!$anArray) is (!true). Inverting true, we have (false) and the condition evaluates to false. The code-block after in the else keyword is run.
Output: The array has information in it.
Although more wordy, the example below removes the haziness, and you can clearly see what I am checking for.
<?php
$anArray = array('first_name' => 'Joe');
// Test to see if this is an array
if (is_array($anArray) === true) {
// Test to see if the array is empty
if (empty($anArray) === true) {
echo("The array is empty.");
}
else {
echo("The array has information in it.");
}
}
else {
echo("This is not an array.");
}
?>
