views:

19

answers:

1

I have the following class:

<?php

/*
* Abstract class that, when subclassed, allows an instance to be used as an array.
* Interfaces `Countable` and `Iterator` are necessary for functionality such as `foreach`
*/
abstract class AArray implements ArrayAccess, Iterator, Countable
{
    private $container = array();

    public function offsetSet($offset, $value) 
    {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    public function offsetExists($offset) 
    {
        return isset($this->container[$offset]);
    }

    public function offsetUnset($offset) 
    {
        unset($this->container[$offset]);
    }

    public function offsetGet($offset) 
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }

    public function rewind() {
            reset($this->container);
    }

    public function current() {
            return current($this->container);
    }

    public function key() {
            return key($this->container);
    }

    public function next() {
            return next($this->container);
    }

    public function valid() {
            return $this->current() !== false;
    }   

    public function count() {
     return count($this->container);
    }

}

?>

Then, I have another class that sub-classes AArray:

<?php

require_once 'AArray.inc';

class GalleryCollection extends AArray { }

?>

When I fill a GalleryCollection instance with data and then try to use it in array_filter(), in the first argument, I get the following error:

Warning: array_filter() [function.array-filter]: The first argument should be an array in

Thanks!

+3  A: 

Because array_filter only works with arrays.

Look at other options, like FilterIterator, or create an array from your object first.

Artefacto
Do you know if it is possible to extend the Array class and use an instance of that extension in `array_filter()`?
letseatfood
It's not possible and `array` is not a class (php 5.3).
VolkerK
@letseatfood, `array_filter` will only work on things that are of the `array` type in PHP… not `object` as any class instances will be. If you want to get an array out of an iterator, use [`iterator_to_array()`](http://php.net/iterator_to_array). To filter the values in the iterator, as Artefacto said, you should be using a `FilterIterator`.
salathe
@Artefacto - Thank-you. I wasn't sure if it was an array or not.
letseatfood
@VolkerK - Ugh I feel silly. @salathe - Thanks VERY MUCH for sharing the `iterator_to_array()` function. With @Artefacto's suggestion to create an array from the object, I was able to do it easily with `iterator_to_array()`.
letseatfood