madkris24
madkris24

Reputation: 493

Callback function for array_filter

class MyClass {
    private function isExist($arr) {
        // need to do some formatting here first

        // need to call in_array here to check whether to filter out duplicates
        return false; // temporary return value
    }

    public function test() {
        $data = array(
            array('foo' => 'alpha', 'bar' => 'bravo'),
            array('foo' => 'charlie', 'bar' => 'delta'),
            array('foo' => 'alpha', 'bar' => 'bravo'),
        );

        $result = array_filter($data, array('MyClass', 'isExist'));
        print_r($result);
    }
}

$obj = new MyClass();
$obj->test();

How to access the array being filtered within the callback function? And is it possible to pass one or two arguments to the callback function?

And I have PHP 5.3.1, just in case you'll need to know the version I am using.

EDIT: // separate formatting and then call array_unique

Upvotes: 0

Views: 1346

Answers (2)

Shadikka
Shadikka

Reputation: 4276

No need to reinvent the wheel here: http://php.net/array-unique

Upvotes: 1

Thariama
Thariama

Reputation: 50832

Try

class MyClass {

    ...

    public function test() {
        $data = array(
            array('foo' => 'alpha', 'bar' => 'bravo'),
            array('foo' => 'charlie', 'bar' => 'delta'),
            array('foo' => 'alpha', 'bar' => 'bravo'),
        );

        $result = array_filter($data, array('MyClass', 'isExist'));
        return $result;
    }
}

$obj = new MyClass();
$array_filterd = $obj->test();

Upvotes: 0

Related Questions