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('memory_limit')
call returns string values like '128M' rather than integers.
I know I can write a function to parse these strings (taking case and trailing 'B's into account) as I have written them numerous times:
function int_from_bytestring ($byteString) {
preg_match('/^\s*([0-9.]+)\s*([KMGTPE])B?\s*$/i', $byteString, $matches);
$num = (float)$matches[1];
switch (strtoupper($matches[2])) {
case 'E':
$num = $num * 1024;
case 'P':
$num = $num * 1024;
case 'T':
$num = $num * 1024;
case 'G':
$num = $num * 1024;
case 'M':
$num = $num * 1024;
case 'K':
$num = $num * 1024;
}
return intval($num);
}
However, this gets tedious and this seems like one of those random things that would already exist in PHP, though I've never found it. Does anyone know of some built-in way to parse these byte-amount strings?
Method 1: Using number_format() Function. The number_format() function is used to convert string into a number. It returns the formatted number on success otherwise it gives E_WARNING on failure. echo number_format( $num , 2);
In PHP you can use intval(string) or floatval(string) functions to convert strings to numbers.
PHP settype() Function The settype() function converts a variable to a specific type.
PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With