A basic Collection Class
Written by: maffelu , 2011-01-18
require_once('Collection.php');
$numbers = new Collection();
//Add one by one
$numbers->add(1);
$numbers->add(3);
//Add several at a time
$numbers->addRange(5, 13, 23, 199);
require_once('Collection.php');
$numbers = new Collection();
$numbers->add(1);
$numbers->add(3);
$numbers->addRange(5, 13, 23, 199);
//Contains checks if the element can be found in the collection
if($numbers->contains(5))
echo "It contains 5! <br />";
else
echo "It doesn't contain 5 :( <br />";
$arr = $numbers->toArray(); //$arr now contains the collection in a pure array form
echo $numbers; //Will run a print_r() on the collection (without <pre> tags)
$numbers->debug(); //Runs a print_r() WITH '<pre>' tags surrounding it
//Output:
//It contains 5!
//Array ( [0] => 1 [1] => 3 [2] => 5 [3] => 13 [4] => 23 [5] => 199 )
//Array
//(
// [0] => 1
// [1] => 3
// [2] => 5
// [3] => 13
// [4] => 23
// [5] => 199
//)
require_once('Collection.php');
$numbers = new Collection();
$numbers->add(1);
$numbers->add(3);
$numbers->addRange(5, 13, 23, 199);
$highNumbers = $numbers->where(function($key, $number)
{
return $number > 10;
});
$highNumbers->debug();
//Output:
//Array
//(
// [0] => 13
// [1] => 23
// [2] => 199
//)
require_once('Collection.php');
$arr = array("Name" => "John", "Age" => 14, "Gender" => "Male");
$person = new Collection($arr);
$vitalInformation = $person->select("Name", "Gender");
$vitalInformation->debug();
require_once('Collection.php');
$collection = new Collection();
$collection->addRange("Foo", "Bar", "Biz");
for($i = 0; $i < count($collection); $i )
{
echo $collection[$i];
}
foreach($collection as $c)
{
echo $c;
}
There are no comments on this article.
If you have any question or just want to leave a message, just fill out the form below!
Your e-mail will not be visible in your post, it is for validation reasons only
Maffelu
Creator and admin of MorkaLork.com.
Started programming in HTML back when frames and tables was the way to design a page, moved on to Pascal/Delphi, PHP, javascript/jQuery, VB.NET/C#, Java and C++.
Currently studies .NET (in general) focusing on ASP.NET.