Reputation: 9294
I have a switch case like this
switch($filesize_in_bytes){
case "10Mb <= $filesize_in_bytes <= 100Mb":
//do some stuff and break;
case "1Gb <= $filesize_in_bytes <= 10Gb":
//do some stuff and break;
}
As you can see $filesize_in_bytes
is in bytes, now how can I convert those values with Mbs and Gbs into bytes? The cases 10Mb, 100Mb, 1Gb and so on
I cant hardcode them directly to bytes and the values too are different based on user status.
The case are fetched from database:
$rule1[0] = '10Mb';
$rule1[1] = '100Mb';
$rule2[0] = '1Gb';
$rule2[1] = '10Gb';
Upvotes: 0
Views: 718
Reputation: 85794
First off, I don't really like this database design. So as not to waste space on byte-level precision by actually storing the limit as an integer (that would require a full BIGINT for things like 100Gb
), you might want to instead do something like limit_amount INT UNSIGNED
and limit_unit ENUM('b','kb','Mb','Gb')
. Then when pulling from the database, you can just do simple math to get the byte value:
$limit_amount = 10; // pull from
$limit_unit = 'Mb'; // database
$units = array('b' => 1, 'kb' => 125, 'Mb' => 125000, 'Gb' => 125000000);
$limit_in_bytes = $limit_amount * $units[$limit_unit];
(Note that this system of units uses kb
and Mb
, which are different from kB
and MB
, the more common units. If you wanted the latter, make the proper conversions!)
That's much more data-efficient than storing as strings, ensures that your users can't put in nonsense units like "5lolCats" when inputting strings, and makes it easy to pull the data back to bytes.
...or you can just use BIGINT. I don't really mind, so as long as you're not storing integer values as strings.
Tahdah. You have pulled the amount from the database as bytes instead of a string, and now you can do a direct integer comparison without magic string compare weirdness.
Upvotes: 1
Reputation: 36999
Take a look at the following PHP script that provides a function to do exactly this:
http://aidanlister.com/2004/04/human-readable-file-sizes/
Upvotes: 0