php When array_push meets static

WBOY
Release: 2023-03-02 09:56:01
Original
1350 people have browsed it

<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>
Copy after login
Copy after login

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>
Copy after login
Copy after login

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.

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!