Passing userdata to array_walk and reference to self

I need to filter a multidimensional array by the search keyword.

I am using array_walk , but I could not send the search keyword inside array_walk to class

multidimensional array

 Array ( [0] => SimpleXMLElement Object ( [plugin_name] => Custom Extension ) [1] => SimpleXMLElement Object ( [plugin_name] => Hello World ) [2] => SimpleXMLElement Object ( [plugin_name] => Test Plugin ) ) 

I tried the following functions:

First

 array_walk($lists, function(&$value, $index){ if (stripos($value->plugin_name, $this->search) === false) unset($lists[$index]); }); 

It gives me Fatal error: Using $this when not in object context in

Second

 $search = $this->search; array_walk($lists, function(&$value, $index){ if (stripos($value->plugin_name, $search) === false) unset($lists[$index]); }); 

I could not get $search var from array_walk function

Third

 $search = $this->search; array_walk($lists, function (&$value, $index) use ($search) { if (stripos($value->plugin_name, $search) !== false) return $value; }); 

$search succeeded with the use keyword, but the $lists array did not change, so it did not reference. Why?

What should I do or use another function instead of array_walk ?

Decision

 $params = array('search' => $this->search, 'data' => $lists); array_walk($lists, function (&$value, $index) use (&$params) { if (stripos($value->plugin_name, $params['search']) === false) unset($params['data'][$index]); }); $lists = $params['data']; 

I sent params with the use keyword as an array and a reference to self.

+6
source share
1 answer

You need to use the use keyword.

 array_walk($lists, function (&$value, $index) use ($search) { 

PHP is not like JavaScript, so the anonymous function is still in a different area, but use used for this. I would have contacted the documentation for use , but it didn't seem to be.

+6
source

Source: https://habr.com/ru/post/953982/


All Articles