0
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

2
  • array_filter iterates over each entry in the array and calls the callback. You cannot pass another parameter. Are you trying to find unique entries in $data? i.e. Do you want $result to contain the first and second entries of $data, but not the third (since it is the same as the first)? Commented Feb 17, 2011 at 13:16
  • "Do you want $result to contain the first and second entries of $data, but not the third (since it is the same as the first)?" - yes, basically im trying to remove duplicate items Commented Feb 17, 2011 at 13:25

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Not sure if I got the answer first before this post was made but yea, I ended up using this function. +1
0

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();

2 Comments

im sorry, the question may have been misleading. I have edited it, kindly take a look.
using array_filter you can only access one element of your array that is used as input paramter for your isExist - you called it '@arr', but it is alwayys only one single array-element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.