Skip to content

How to use array_map() with class method?

Using array_map() function is pretty simple in procedural style coding in PHP, while coding in object oriented fashion is also easy but bit tricky. So here i would like to share simple example on using class method as a callback to the array_map() function.

Syntax :

//Regular functions:
array_map('MyFunction', $array);

//static functions in a class:
array_map(array('MyClass', 'MyFunction'), $array);

//functions from an object:
array_map(array($this, 'MyFunction'), $array);

//functions from an parent class 
array_map(array($this, 'parent::MyFunction'), $array);
  

Example :

 'Arjun+PHP','website' => 'arjunphp+.com');

$classObject = new MyClass();
$newArray = $classObject->filterMyArray($array);
print_r($newArray); 
/* output : Array(
		[name] => ArjunPHP
		[website] => arjunphp.com
)
*/

That’s it.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments