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
Share on other sites

Quite complicated if you ask me, would take some thinking power! This topic may be better suited to the freelance section? Unless someone's done this before? I'll keep thinking but every idea I have at the minute is a dead end! Sorry pal!

 

Adam

Link to comment
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.