Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert some character into numeric in php?

Tags:

php

I need help to change a character in php. I got some code from the web:

char dest='a';
int conv=(int)dest;

Can I use this code to convert a character into numeric? Or do you have any ideas? I just want to show the result as a decimal number:

if null == 0
if A == 1
like image 716
klox Avatar asked Aug 27 '10 02:08

klox


2 Answers

Use ord() to return the ascii value. Subtract 96 to return a number where a=1, b=2....

Upper and lower case letters have different ASCII values, so if you want to handle them the same, you can use strtolower() to convert upper case to lower case.

To handle the NULL case, simply use if($dest). This will be true if $dest is something other than NULL or 0.

PHP is a loosely typed language, so there is no need to declare the types. So char dest='a'; is incorrect. Variables have $ prefix in PHP and no type declaration, so it should be $dest = 'a';.

Live Example

<?php

    function toNumber($dest)
    {
        if ($dest)
            return ord(strtolower($dest)) - 96;
        else
            return 0;
    }

      // Let's test the function...        
    echo toNumber(NULL) . " ";
    echo toNumber('a') . " ";
    echo toNumber('B') . " ";
    echo toNumber('c');

      // Output is:
      // 0 1 2 3
?>

PS: You can look at the ASCII values here.

like image 93
Peter Ajtai Avatar answered Oct 22 '22 03:10

Peter Ajtai


It does indeed work as in the sample, except that you should be using php syntax (and as a sidenote: the language that code you found most probably was, it did not do the same thing).

So:

$in = "123";
$out = (int)$in;

Afterwards the following will be true:

$out === 123
like image 22
Jasper Avatar answered Oct 22 '22 03:10

Jasper