Audit my Code - Data converstions?

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
Daz
Forum Newbie
Posts: 18
Joined: Thu Mar 19, 2009 2:12 am

Audit my Code - Data converstions?

Post by Daz »

I was curious if there are other/better ways to code the following (it's a function to convert data sizes):

Code: Select all

    function convert_data( $number, $unit0, $unit1 )
    {   // Base unit is megabytes
        $d = array();
        $d['bit']                   = 1/(2^23);
        $d['b'] = $d['byte']        = 1/(2^20);
        $d['kbit'] = $d['kilobit']  = 1/(2^13);
        $d['kb'] = $d['kilobyte']   = 1/(2^10);
        $d['mbit'] = $d['megabit']  = 1/(2^3);
        $d['mb'] = $d['megabyte']   = 2^0;
        $d['gbit'] = $d['gigabit']  = 2^3;
        $d['gb'] = $d['gigabyte']   = 2^10;
        $d['tbit'] = $d['terabit']  = 2^13;
        $d['tb'] = $d['terabyte']   = 2^20;
        $d['pbit'] = $d['petabit']  = 2^23;
        $d['pb'] = $d['petabyte']   = 2^30;
        $d['ebit'] = $d['exabit']   = 2^33;
        $d['eb'] = $d['exabyte']    = 2^40;

        $t = (array_key_exists($unit0, $d) AND array_key_exists($unit0, $d))? ($number * $d[$unit0]) / $d[$unit1]: FALSE;
        unset($d);
        return $t;
    }
thanks!
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Re: Audit my Code - Data converstions?

Post by josh »

It isn't clear from the function's signature what the parameters are supposed to be for.

Imagine seeing this in your code complete
function convert_data( $number, $unit0, $unit1 )

Maybe its from and to? do I pass in some sort of integer? A string? Which is which? Am I even correct in my assumption. The code itself looks fine I didn't read it in detail. I could probably figure out how to use it if I read it more, but that means the code can be improved - so I think I've looked at it enough to offer my opinion. Looks decent. Could have more descriptive & obvious signature.
Post Reply