views:

110

answers:

3

I don't know if a array is really a object on php ... but, what I want is to change the array behavior on a foreach loop.

Something similar to this on java:

for( String it : myArr = new Array_Iterator( array) implements Iterator{
    public Array_Iterator( String[] arr){ this.arr = arr}
    /* interface implementation */
}){
    /* loop */
}

What I really want to accomplish is a kind of filter, so that I don't get entries from the array that I don't want

+3  A: 

You are probably looking for the PHP function array_filter.

Iterates over each value in the input array passing them to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.

If you like the iterator based approach you could also take a look at the Standard PHP Library (SPL), in particular ArrayIterator in conjunction with FilterIterator.

cballou
+1  A: 

If what you want is a kind of filter for elements of an array, try array_filter. Make a function that returns true if the element is to be kept or false if it is not to be kept, then pass it to array_filter.

avpx
+1  A: 

Just wrap the Array into an ArrayIterator and you're free to overwrite the regular methods. The Spl provides a number of other Iterators and Interfaces you might find useful. To filter arrays through iterators, use could use the FilterIterator.

Example from PHP Manual:

<?php
// This iterator filters all values with less than 10 characters
class LengthFilterIterator extends FilterIterator {
    public function accept() {
        // Only accept strings with a length of 10 and greater
        return strlen(parent::current()) > 10;
    }
}

$arrayIterator = new ArrayIterator(array('test1', 'more than 10 characters'));
$lengthFilter = new LengthFilterIterator($arrayIterator);

foreach ($lengthFilter as $value) {
    echo $value . "\n"; // ignores "test1" in array
}
Gordon