7

I've never used the array_filter function before so giving it a go by no matter what I use as the function name it is giving me the error

Warning: array_filter() expects parameter 2 to be a valid callback, function 'odd' not found or invalid function name in

I have even taken the steps of copying paste the example directly off the php manual page and it is giving me that same error. Code:

function odd($var) {
    // returns whether the input integer is odd
    return($var & 1);
 }

function calculate($res, $period, $elements, $per, $total, $brand = false) {

    $array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
    $array2 = array(6, 7, 8, 9, 10, 11, 12);

    echo "Odd :\n";
    print_r(array_filter($array1, "odd"));
}

I really don't know where to go here. Usually when I'm having trouble I can copy and paste the code exact off the php manual page and work my way back from there but if their example isn't even working it makes it hard.

5
  • 2
    Hm? It works just fine for me, what's your PHP version? Commented Dec 20, 2012 at 6:45
  • Appears to be working codepad.org/GV2Kyp89. Is that the exact code or did you trim it down before posting? Commented Dec 20, 2012 at 7:05
  • Can you restart PHP & Apache .. it works fine on 4.3.0 - 5.4.9 Commented Dec 20, 2012 at 7:05
  • 1
    @YannisRizos php 5.4.4 on MAMP. Back into work today and it still giving me the same warning. I isolated the code completely in it's own program and it worked... I have no idea why it's not working within the class I have written. There are no other functions called "odd" so it can't be that Commented Dec 20, 2012 at 21:59
  • Show us how both your class and these functions are defined. Commented Mar 21, 2014 at 21:56

2 Answers 2

12

I think in your case, function odd is not a standalone function but method of your class. In that case you should write

print_r(array_filter($array1, array($this,"odd")));

to run odd method from your class

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

Comments

0

If your class is the same and you call a method in recursive then the PHP does not know the method belongs each class or not that's why use $this in an array:

array_filter($array1, array($this,"recursive"))

    public function customArrayFilter($logDate, $uid, $date)
    {
        $logDates = array($logDate);
        $result = array_filter($logDates, array($this, "recursive"));
        var_dump($result);
    }

    public function recursive($data)
    {
        return $data;
    }

   $this->customArrayFilter($data, 1, '2019-02-23');

Comments

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.