Home  >  Article  >  Backend Development  >  php When array_push meets static

php When array_push meets static

WBOY
WBOYOriginal
2016-12-01 01:27:191351browse

<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?

Reply content:

<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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn