How to use RegexIterator in PHP

There are a couple of different ways of going about something like this, I’ll give two quick approaches for you to choose from: quick and dirty, versus longer and less dirty (though, it’s a Friday night so we’re allowed to go a little bit crazy). 1. Quick (and dirty) This involves just writing a regular … Read more

How can I retrieve the full directory tree using SPL?

By default, the RecursiveIteratorIterator will use LEAVES_ONLY for the second argument to __construct. This means it will return files only. If you want to include files and directories (at least that’s what I’d consider a full directory tree), you’d have to do: $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST ); and then you can foreach … Read more

What is Autoloading; How do you use spl_autoload, __autoload and spl_autoload_register?

spl_autoload_register() allows you to register multiple functions (or static methods from your own Autoload class) that PHP will put into a stack/queue and call sequentially when a “new Class” is declared. So for example: spl_autoload_register(‘myAutoloader’); function myAutoloader($className) { $path=”/path/to/class/”; include $path.$className.’.php’; } //————————————- $myClass = new MyClass(); In the example above, “MyClass” is the name … Read more

How does RecursiveIteratorIterator work in PHP?

RecursiveIteratorIterator is a concrete Iterator implementing tree traversal. It enables a programmer to traverse a container object that implements the RecursiveIterator interface, see Iterator in Wikipedia for the general principles, types, semantics and patterns of iterators. In difference to IteratorIterator which is a concrete Iterator implementing object traversal in linear order (and by default accepting … Read more

How can I sort arrays and data in PHP?

Basic one dimensional arrays $array = array(3, 5, 2, 8); Applicable sort functions: sort rsort asort arsort natsort natcasesort ksort krsort The difference between those is merely whether key-value associations are kept (the “a” functions), whether it sorts low-to-high or reverse (“r“), whether it sorts values or keys (“k“) and how it compares values (“nat” … Read more