Friday 24 August 2007

PHP Basics (Section 2) - Functions & String



Function

  1. We use functions for several major reasons: readability, code separation, maintainability, modularity.
  2. In PHP4 objects were thrown around ByVal, this meant that you made copies without even thinking about it.
  3. In PHP5 objects are always passed BrRef unless you explicitly clone it, keep that in mind.
  4. Return statements can exist anywhere anywhere within the function, and you can even have multiple return values.
  5. Avoid situations where the same function may return nothing, or something.
String
  1. Strings are the most commonly used variable type in PHP, because they are both central to web development, and the common method of data transmission from the user
  2. Within strings many characters take a special meaning, matching quotes, back slashes, octal numbers, variables, if you wish to accept them as they are you mush escape them with the \ character.
  3. strcmp() - Compare two strings. Returns > 0 if $string_1 is greater than $string_2, and 0 if they are equal.
  4. strcasecrm() - Case insensitive version of strcmp()
  5. substr() - Used to retrieve a portion of a string
  6. number_format() - By default formats a number with the comma as the thousands separator, and no decimal.
  7. preg_match() - Returns the number of matches found by a given search string under this format, also capable of returning the match.
Examples:

echo number_format("1234567.123"); //Shows 1,234,567
echo number_format("1234567.123", 3, ",", " "); //Shows 1 234 567.123

$string = "156 abc";
var_dump(preg_match("/\w\s\w/", $string)); // 1 (matches)


No comments: