Jump to content

int into string


aximbigfan

Recommended Posts

I need a function that will receive an int, and transform it into a letter representation.

 

PHP can do a neat thing, where it will increment a string, as so...

a

b

c

d

...

z

aa

ab

ac

ad

.

 

What I need to do, is convert this into an int. For example, aa would be 27, ab would be 28, a would be 1, b would be 2, you get it.

 

I also need to convert a number into this kind of representation.

 

Any ideas?

 

Thanks,

Chris

Link to comment
https://forums.phpfreaks.com/topic/134339-int-into-string/
Share on other sites

From PHPExcel:

    public static function columnIndexFromString($pString = 'A')
    {
    	// Convert to uppercase
    	$pString = strtoupper($pString);

    	// Convert column to integer
    	if (strlen($pString) == 1) {
    		return (ord($pString{0}) - 64);
    	} elseif (strlen($pString) == 2) {
    		return $result = ((1 + (ord($pString{0}) - 65)) * 26) + (ord($pString{1}) - 64);
    	} elseif (strlen($pString) == 3) {
		return ((1 + (ord($pString{0}) - 65)) * 676) + ((1 + (ord($pString{1}) - 65)) * 26) + (ord($pString{2}) - 64);
    	} else {
    		throw new Exception("Column string index can not be " . (strlen($pString) != 0 ? "longer than 3 characters" : "empty") . ".");
    	}
    }

    public static function stringFromColumnIndex($pColumnIndex = 0)
    {
        // Convert column to string
        $returnValue = '';
        // Determine column string
        if ($pColumnIndex < 26) {
        	$returnValue = chr(65 + $pColumnIndex);
        } else {
        	$iRemainder = (int)($pColumnIndex / 26) -1;
        	$returnValue = PHPExcel_Cell::stringFromColumnIndex($iRemainder).chr(65 + $pColumnIndex%26) ;
        }
        // Return
        return $returnValue;
    }

Link to comment
https://forums.phpfreaks.com/topic/134339-int-into-string/#findComment-699634
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.