Home >Backend Development >PHP Tutorial >php When array_push meets static
<code>public function find_children_cat($cat_id, $data) { static $tem=array(); foreach ($data as $val) { if ( $val['parent_id'] == $cat_id ) { array_push($tem, $val['cat_id']); $this->find_children_cat($val['cat_id'], $data); } } return $tem; }</code>
With static array_push, there will be no duplicate values. Generally, array_push will have duplicate values as long as the same value is pushed;
Why won’t duplicate values appear after using static?
<code>public function find_children_cat($cat_id, $data) { static $tem=array(); foreach ($data as $val) { if ( $val['parent_id'] == $cat_id ) { array_push($tem, $val['cat_id']); $this->find_children_cat($val['cat_id'], $data); } } return $tem; }</code>
With static array_push, there will be no duplicate values. Generally, array_push will have duplicate values as long as the same value is pushed;
Why won’t duplicate values appear after using static?
I haven’t looked at the specific code. I don’t care whether there are duplicate values. Normally, the variables in the function will be released after the function ends, but when you set the variable to staitc
in the function, it will not be static variables. It exists within the entire function scope. Every time you call the function, the value of the variable will be retained.