Documentation
Miguel Esteves edited this page Oct 4, 2019
·
4 revisions
The usage is very simple and straightfoward, lets see:
$friendsAge = new Collection();
Collection provides 2 methods for adding data.
- By array operator.
- By function.
When using collection add
function, you can chain functions.
// By Array Operator.
$friendsAge["andrew"] = 23;
$friendsAge["bob"] = 28;
$friendsAge["carl"] = 26;
// You can chain functions.
$friendsAge->add("diana", 23)
->add("earl", 18)
->add("frank", 26);
To delete data you can use 3 ways:
- Collection
remove
function. - Php
unset
function. - Collection
clear
function.
unset($friendsAge["franklin"]);
// You can chain functions.
$friendsAge->remove("joey")
->remove("andrew");
// Clear entire collection
$friendsAge->clear();
Whenever you want to update a value in your collection you can do it with two different ways:
- By array operator.
- By function
Note: When you use update
function, if the key doesnt exist, this one will be added to your collection.
$friendsAge["franklin"] = 20;
// With associative key access.
$friendsAge->update("franklin", 20);
// With index access. update(index, value);
$friendsAge->update(3, 48);
$friendsAge["franklin"];
// Using associative key.
$friendsAge->get("franklin");
// Using index.
$friendsAge->get(1);
/* This function accepts a callable with two parameters $key and $value.
You can map the return with a boolean value to get specific value.
*/
$mySpecificValue = $friendsAge->find(function($key, $value){
return ($value == '20'); // returns the first value thats equals to '20'.
});
$mySpecificValue = $friendsAge->find(function($key, $value){
return ($key == 'earl' || $key == 'john'); // returns the first one of the two values.
});
// Returns an array with collection values.
$valuesArray = $friendsAge->getAll();
// Returns the index of the given associative key.
$index = $friendsAge->indexOf("franklin");
// Returns the associative key of the given index.
$key = $friendsAge->keyOf(2);
// Returns true or false if the offset exists.
// With associative key
$friendsAge->offsetExists("franklin");
// With index
$friendsAge->offsetExists(1);
// Returns all associative keys
$keys = $friendsAge->getOffsets();
// Get the number of elements in your collection.
$size = $friendsAge->count();
/* This function accepts as argument a callable object.
This callable object contains 2 parameters, one for the offset and the other for the value.
If you return anything inside the callable, you will receive those values back stored in a array.
*/
$myReturnedValuesArray = $friendsAge->each(function($key, $value){
return "{$key} is {$value} old!";
});
foreach($friendsAge as $friend => $age){
echo "{$friend} is {$age} old!";
}
$value = $friendsAge->serialize();
$friendsAge->unserialize($value);
$json = $friendsAge->toJson();
$friendsAge->fromJson($json);
$json = json_encode($friendsAge);