Zend PHP5 certification Exam study review 10: Supplementary I

Since I mentioned before, I didn’t included the Language Basic and Function topics in these series of reviews, because I think you should already have a good knowledge about them. Anyway, if you have more time, then you can following this post to review some of these features in PHP. It mainly includes PHP’s String(since it is so important), Array, and Function feature; also, it contain some extra information just I think worthy to be reminded.

.Single line comments are ended by either the newline character or a closing PHP tag, so a single like comment like:
// This tag ?> can end PHP code
Can have unintended output.


PHP has a large collection of built in functions to handle strings, we’ve looked at strings already, let’s look at different ways to interact with them in greater detail:

strlen(), Returns the length of the string passed to it:

echo strlen(‘Jello’); //5
$a = array(“Hello World”, “a”);
echo strlen($a); //5

str_replace() & strtr()
Searches the given string for the needle, replacing it with the presented string:

echo str_replace(“a”, “b”, “abc”); //bbc
echo str_replace(array(‘a’,’b’,’c’), array(‘b’,’c’,’a’), ‘abc’); //aaa
echo strtr(‘abc’,’ab’,’bc’); //bcc

strcmp() & strcasecmp()

These functions compare two strings, returning zero when they match, greater than one when string 1 > string 2, and less than one when string 1 < string 2:

echo strcmp(‘hello’, ‘Hello’); // > 1
echo strcasecmp(‘hello’, ‘Hello’); // 0

strpos() & strstr()
strpos will return the position of the search string within the target. strstr will return the portion of target from the beginning of the first match until the end. Both function have case
insensitive counterparts:

echo strpos(‘hello new world’, ‘new’); //6
echo strstr(‘hello new world’, ‘new’); //new world

strspn() & strcspn()
Apply a mask to a given string, strspn() returns the number of characters matching the mask, strcspn() uses a blacklist and returns the number of non-matching characters:

$mask = “abcdefg “;
$string = “beg bad fed billy”; //strlen($string) = 17
echo strspn($string, $mask); //13
$mask = “abcdefg”;
$string = “joy to the world”; //strlen($string) = 16
echo strcspn($string, $mask); //9

substr() – Used to retrieve a portion of a string

$string = “I am the very model of the modern major
echo substr($string, 2);
//am the very model of the modern major general
echo substr($string, 9, 10); //very model
echo substr($string, -7); //general
echo substr($string, 5, -8);
//the very model of the modern major

If start is non-negative, the returned string will start at the start’th position in string, counting from zero. For instance, in the string ‘abcdef’, the character at position 0 is ‘a’, the character at position 2 is ‘c’, and so forth.
If start is negative, the returned string will start at the start’th character from the end of string.

If string is less than or equal to start characters long, FALSE will be returned.

If length is given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of string).
If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a start is negative). If start denotes a position beyond this truncation, an empty string will be returned.

Printf formatting specifiers:

% – a literal percent character. No argument is required.
b – the argument is treated as an integer, and presented as a binary number.
c – the argument is treated as an integer, and presented as the character with that ASCII value.
d – the argument is treated as an integer, and presented as a (signed) decimal number.
e – the argument is treated as scientific notation (e.g. 1.2e+2).
u – the argument is treated as an integer, and presented as an unsigned decimal number.
f – the argument is treated as a float, and presented as a floating-point number (locale aware).
F – the argument is treated as a float, and presented as a floating-point number (non-locale aware). Available since PHP 4.3.10 and PHP 5.0.3.
o – the argument is treated as an integer, and presented as an octal number.
s – the argument is treated as and presented as a string.
x – the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
X – the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

Complex (curly) syntax
This isn’t called complex because the syntax is complex, but because you can include complex expressions this way.
In fact, you can include any value that is in the namespace in strings with this syntax. You simply write the expression the same way as you would outside the string, and then include it in { and }. Since you can’t escape ‘{‘, this syntax will only be recognised when the $ is immediately following the {. (Use “{\$” to get a literal “{$”).

Which syntax is preferred in PHP5? $a[0] or $a{0}
The {} syntax is depreciated in PHP 6.

strlen(null); //0


$a = array(5=>”b”, 7, 9, “23” => ‘c’, ‘j’);
$b = array(1, 2, 3, ‘f’, ‘fred’ => $a);
How do I access the value:
– 7 // $a[6];
– ‘c’ // $a[“23”];
– ‘b’ through the array $b // $b[‘fred’][5]
– ‘f’ // $b[3]

Array Iteration
When iterating through an array via foreach() keep in mind it operates on a copy of the array.
.In PHP 5 items can be iterated over by reference rather than simply by value

foreach($array AS &$value) { … }

Using the internal array pointer doesn’t have this problem:
end() – Move pointer to last element
key() – Retreives key from current position
next() – Advances array pointer one spot then returns current value
prev() – Rewinds the array pointer one spot, then returns the current value
reset() – Resets the array pointer to the beginning of the array
each() – Returns the current key and value from the array, then iterates

Sorting Arrays
Sorting arrays comes up frequently, but can be frequently be offloaded to an external system (databases are a common system) which may be able to do it faster.
The type of sorting that must be done depends entirely on the data contained within the array.
This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.
This function assigns new keys for the elements in array. It will remove any existing keys you may have assigned, rather than just reordering the keys.
Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays.
Sort an array and maintain index association

array_push() array_unshift()
array_pop() array_shift()

In associative arrays strings are used to key the data, keys containing only digits are cast to integers.

array_keys() & array_values()

bool array_walk ( array &$array, callback $funcname [, mixed $userdata] )
Applies the user-defined function funcname to each element of the array array. Typically, funcname takes on two parameters. The array parameter’s value being the first, and the key/index second. If the optional userdata parameter is supplied, it will be passed as the third parameter to the callback funcname.

Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.

You can merge arrays using array_merge(), when different associative arrays have duplicate keys, the values in the rightmost array take precedence.

Cut out a chunk of an array

merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.

If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.

.SQLite is a database, without the database.
.Basically, rather than using a separate program to persistently maintain the database, SQLite on the other hand requires the C libraries that comprise the DB to be built into whatever program would like to use them.
.SQLite was built into PHP by default as of PHP5, which is cool, some twits turn it off, which isn’t.
.It’s fast, free, and has nice licensing terms.

Apart from not needing to connect to a remote server or process, SQLite is no different from other database systems:

$db = sqlite_open(‘mysqlitedb’, 0666, $sqliteerror)
sqlite_query($db, ‘CREATE TABLE foo (bar varchar(10))’);
sqlite_query($db, “INSERT INTO foo VALUES (‘fnord’)”);
$result = sqlite_query($db, ‘select bar from foo’);

Take a look at the manual pages for more information on the function library.

.Recent versions of PHP no longer ship with the MySQL extension built in, you must enable it at configure time.
.We new have two versions of the MySQL extension available, MySQL and MySQLi.
.The MySQLi extension makes some of MySQL’s more recent functionality available, things like prepared statements.

.Objects can be used to merge togethor data and the methods that manipulate it.
.You can define the interface of an object using either abstract classes or interfaces
.Abstract classes can define the methods that extending classes must offer by declaring them with the abstract keyword. They may also create their own methods.

.Interfaces simply define the methods that an implementing object must include.

abstract class example
public $name;
abstract public function displayExample();
abstract protected function prepExample();
public function __construct($name)
$this->name = $name;
class myExample extends example
public function displayExample() { echo $this->name; }
public function prepExample() {
$this->name = md5($this->name);}

interface inputData
public function alpha ($data);
public function alnum ($data);
interface outputData
public function web ($data);
public function sql ($data);
class templateEngine implements inputData, outputData
public function alpha($a) {}
public function alnum($b) {}
public function web($c, $d = “”) {}
public function sql($e) {}
public function iStillWork() {}

Built in Interfaces
[0] => Traversable
[1] => IteratorAggregate
[2] => Iterator
[3] => ArrayAccess
[4] => Serializable
[5] => RecursiveIterator
[6] => OuterIterator
[7] => SeekableIterator
[8] => Countable
[9] => SplObserver
[10] => SplSubject
[11] => Reflector

Create an abstract class, extend it
– Can you define an abstract method as private? Yes, but not useful. Because extended classes can’t see it/them anyway.
Create an interface, implement it
– Can you define an interface as having private methods? I think no, them all must be public, not even protect.
Implement the Iterator interface
– foreach() over your new object 🙂
Play with some of those string and array function.

5 Comments - Leave a comment
  1. Kirill says:

    Could you explain why str_replace(array(‘a’,’b’,’c’),array(‘b’,’c’,’a’),’abc’) returns ‘aaa’ string instead of ‘bca’ ? Simply can`t understand thist trick!

  2. David Adam says:

    This is why:

    The first time, str_replace replace the “a” to “b” in string “abc”, so it becomes: “bbc”;
    The second time, str_replace replace the “b” to “c” in string “bbc”, so it becomes: “ccc”;
    The third time, str_replace replace the “c” to “a” in string “ccc”, so it becomes: “aaa”;

    The trick is each replace, the subject changes.

    Hope you understand now.


  3. Henry Lu says:

    Hi admin,
    About the question “Can you define an abstract method as private?”. I don’t think abstract method can be private, as a private method can’t be inherited.

Leave a Reply

Your email address will not be published. Required fields are marked *