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

Or some shorter version, if you please

function toInteger ($string)
{
    sscanf ($string, '%u%c', $number, $suffix);
    if (isset ($suffix))
    {
        $number = $number * pow (1024, strpos (' KMG', strtoupper($suffix)));
    }
    return $number;
}

I think you're out of luck. The PHP manual for ini_get() actually addresses this specific problem in a warning about how ini_get() returns the ini values.

They provide a function in one of the examples to do exactly this, so I'm guessing it's the way to go:

function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    switch($last) {
        // The 'G' modifier is available since PHP 5.1.0
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }

    return $val;
}

They have this to say about the above function: "The example above shows one way to convert shorthand notation into bytes, much like how the PHP source does it."


From the PHP website for ini_get():

function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    switch($last) {
        // The 'G' modifier is available since PHP 5.1.0
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }

    return $val;
}

Tags:

Php