phpfunctionclassarray-walk

How to use array_walk() with a function which belongs to a class?


I'm trying to apply a function to every item in an array in PHP. However, this function is contained in another file, containing a class.

I have included the file, and the function can be called easily enough. It just won't work with array_walk. The way I'm trying to do this is...

$new_variable_array = array_walk($variable_array, $class->function);

Solution

  • Ah sorry it's array_walk, ignore my comments, here is an answer. Since in array_walk you show the function name as a string containing the function name, when using a class method you need to do it inside an array, where the first element of the array is the class to be used, and the 2nd part is a string containing the method's name. I hope this works for you.

    
    //This is my class
    $myClass = new MyClass;
    
    //This is my array
    $variable_array = array();
    
    //Array walk like so
    array_walk($variable_array, array($myClass, 'functionName'));
    

    Here is a working example, check that yours fits the same rules / parameters.

    
    //My class
    class myClass{
        public function addSurname(&$name, $key, $surname){
            $name = "$name $surname";
        }
    }
    
    //Instantiate the class
    $myClass = new myClass;
    
    //Array
    $array = array('John', 'Mary', 'Jimbob', 'Juan');
    
    //Add the surname to each array element
    array_walk($array, array($myClass, 'addSurname'), 'Jones');
    
    //Show the array
    foreach($array as $x){
        echo $x . '<br />';
    }