25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

78 ” Strings And Patterns<br />

Note that string character indices are zero-based—meaning that the first character of<br />

an arbitrary string $s has an index of zero, and the last has an index of strlen($s)-1.<br />

Comparing, Searching and Replacing Strings<br />

Comparison is, perhaps, one of the most common operations performed on<br />

strings. At times, <strong>PHP</strong>’s type-juggling mechanisms also make it the most maddening—particularly<br />

because strings that can be interpreted as numbers are often transparently<br />

converted to their numeric equivalent. Consider, for example, the following<br />

code:<br />

$string = ’123aa’;<br />

if ($string == 123) {<br />

// The string equals 123<br />

}<br />

You’d expect this comparison to return false, since the two operands are most definitely<br />

not the same. However, <strong>PHP</strong> first transparently converts the contents of<br />

$string to the integer 123, thus making the comparison true. Naturally, the best way<br />

to avoid this problem is to use the identity operator === whenever you are performing<br />

a comparison that could potentially lead to type-juggling problems.<br />

In addition to comparison operators, you can also use the specialized functions<br />

strcmp() and strcasecmp() to match strings. These are identical, with the exception<br />

that the former is case-sensitive, while the latter is not. In both cases, a result of zero<br />

indicates that the two strings passed to the function are equal:<br />

$str = "Hello World";<br />

if (strcmp($str, "hello world") === 0) {<br />

// We won’t get here, because of case sensitivity<br />

}<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)<br />

if (strcasecmp($str, "hello world") === 0) {<br />

// We will get here, because strcasecmp()<br />

// is case-insensitive<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!