_array

05 June 2008 // php. things.

_array is a (yet another) attempt to create object oriented API for php arrays.

download

 

_array is a class that provides a set of simple and "fluent" methods.

For example, this "raw php" code is verbose and inconsistent.

$a = explode(' ', 'FOO BAR');
$a = array_map('strtolower', $a);
sort($a);
echo implode(', ', $a); # "bar, foo"

Using _array, the same is as simple as:

echo _w('FOO BAR')->map('strtolower')->sort(); # "bar, foo"

Another example:

// read users from db
$qry = mysql_query("SELECT * FROM user");
$users = array();
while($rec = mysql_fetch_assoc($qry))
    $users[] = $rec;

// create list of names
$names = array();
foreach($users as $rec)
    $names[] = $users['name'];

// remove admin
$n = array_search('admin', $names);
if($n !== false)
    array_splice($names, $n, 1);

// format and print
$names = array_map('ucfirst', $names);
sort($names);
echo implode("<br>", $names);

with _array, this will be only two lines:

$users = _array()->from_call('mysql_fetch_assoc', mysql_query("SELECT * FROM user"));
echo $users->pluck('name')->remove('admin')->map('ucfirst')->sort()->join("<br>");

download

compact version (with comments stripped)

documentation

test file (requires testik)

 
If you think this comment is spam or otherwise completely irrelevant here, feel free to hide it. The comment disappears immediately, though it is not deleted, so I have an option to "unhide" it later.
 

comment on this