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';
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 likelimit_amount INT UNSIGNEDandlimit_unit ENUM('b','kb','Mb','Gb'). Then when pulling from the database, you can just do simple math to get the byte value:(Note that this system of units uses
kbandMb, which are different fromkBandMB, 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.