Home > Backend Development > PHP Tutorial > PHP built-in function uses compact()

PHP built-in function uses compact()

不言
Release: 2023-03-24 11:26:01
Original
3441 people have browsed it

The content of this article is about the use of compact() in PHP built-in functions. It has a certain reference value. Now I share it with you. Friends in need can refer to it.

I found one when using tpshop today. The PHP built-in function is called compact(). This function creates an array composed of variables taken by the parameters. If there is an array in the parameter, the value of the variable in the array will also be obtained.

This can reduce the amount of code. For example, if

    /**
     * 获取购物车的价格详情
     * @param $cartList|购物车列表
     * @return array
     */
    public function getCartPriceInfo($cartList = null) {
        $total_fee = $goods_fee = $goods_num = 0; //初始化数据。商品总额/节约金额/商品总共数量
        if ($cartList) {
            foreach ($cartList as $cartKey => $cartItem) {
                $total_fee += $cartItem['goods_fee'];
                $goods_fee += $cartItem['cut_fee'];
                $goods_num += $cartItem['goods_num'];
            }
        }
        $result = array(
            'total_fee' => $total_fee,
            'goods_fee' => $goods_fee,
            'goods_num' => $goods_num,
        );
        return $result;
    }
Copy after login



is changed to this, the code will be much simpler.


    /**
     * 获取购物车的价格详情
     * @param $cartList|购物车列表
     * @return array
     */
    public function getCartPriceInfo($cartList = null){
        $total_fee = $goods_fee = $goods_num = 0;//初始化数据。商品总额/节约金额/商品总共数量
        if($cartList){
            foreach ($cartList as $cartKey => $cartItem) {
                $total_fee += $cartItem['goods_fee'];
                $goods_fee += $cartItem['cut_fee'];
                $goods_num += $cartItem['goods_num'];
            }
        }
        return compact('total_fee', 'goods_fee', 'goods_num');
    }
Copy after login

Related recommendations:

How to use PHP built-in function fgets() to read pointer files in detail

The above is the detailed content of PHP built-in function uses compact(). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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