Page 83 - Open Soource Technologies 304.indd
P. 83
Open Source Technologies
Notes $str{1} = “n”;
$str = $str . “i”;
print $str;
Tip: For many cases, PHP has string manipulation functions which use efficient algorithms.
You should first look at them before you access strings directly using string offsets. They
are usually prefixed with str_. For more complex needs, the regular expressions functions—
most notably the pcre_ family of functions—will come in handy.
In PHP 4, you could use [] (square brackets) to access string offsets. This
support still exists in PHP 5, and you are likely to bump into it often. However,
you should really use the {} notation because it differentiates string offsets
from array offsets and thus, makes your code more readable.
6.1.2.5 Booleans
Booleans were introduced for the first time in PHP 4 and didn’t exist in prior versions. A Boolean
value can be either true or false. As previously mentioned, PHP automatically converts types
when needed. Boolean is probably the type that other types are most often converted to behind
the scenes. This is because, in any conditional code such as if statements, loops, and so on, types
are converted to this scalar type to check if the condition is satisfied. Also, comparison operators
result in a Boolean value.
Consider the following code fragment:
$numerator = 1;
$denominator = 5;
if ($denominator == 0) {
print “The denominator needs to be a non-zero number\n”;
}
The result of the equal-than operator is a Boolean; in this case, it would
be false and, therefore, the if() statement would not be entered.
Now, consider the next code fragment:
$numerator = 1;
$denominator = 5;
if ($denominator) {
/* Perform calculation */
} else {
print “The denominator needs to be a non-zero number\n”;
}
78 LOVELY PROFESSIONAL UNIVERSITY