Home > Backend Development > PHP Tutorial > php When array_push meets static

php When array_push meets static

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-03-02 09:56:01
Original
1419 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
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template