Is there an easy way in PHP to convert from strings like '256M', '180K', '4G' to their integer equivalents?

前端 未结 6 599
抹茶落季
抹茶落季 2021-01-08 01:22

I need to test the value returned by ini_get(\'memory_limit\') and increase the memory limit if it is below a certain threshold, however this ini_get(\'me

6条回答
  •  梦谈多话
    2021-01-08 01:49

    even if the solutions above are correct, the switch statement without a break is not very intuitive and for an improved readability, to express what is really going on, I would rather do it this way:

    /**
     * @return int maximum memory limit in [byte]
     */
    private static function takeMaximumFootprint()
    {
        $memory = ini_get('memory_limit');
        $byte = intval($memory);
        $unit = strtolower($memory[strlen($memory) - 1]);
        switch ($unit) {
            case 'g':
                $byte *= 1024 * 1024 * 1024; break;
            case 'm':
                $byte *= 1024 * 1024; break;
            case 'k':
                $byte *= 1024; break;
        }
    
        return $byte;
    }
    

提交回复
热议问题