In PHP, I know there is no official way to delete items once they have been put into an array. But there must be a “best-method” solution to my problem. I believe this may lie in the array_filter function.
Essentially, I have a shopping cart object that stores items in a hashtable. Imagine you can only ever buy one of any item at a time.
I do
add_item(1);
add_item(2);
remove_item(1);
get_count() still returns 2.
var $items;
function add_item($id) {
$this->items[$id] = new myitem($id);
}
function remove_item($id) {
if ($this->items[$id]) {
$this->items[$id] = false;
return true;
} else {
return false;
}
}
function get_count() {
return count($this->items);
}
What do people think is the best method to use in get_count? I can’t figure out the best way to use array_filter that simply doesn’t return false values (without writing a seperate callback).
Thanks 🙂
No official way? Sure there is! Unset!
Also, is this PHP4? Because if not, you should look into some of the SPL stuff like ArrayObject or at least the the Countable and ArrayAccess interfaces.
EDIT
Here’s a version using the interfaces directly
And here’s a version as an implementation of ArrayObject