user3450126 user3450126 - 7 months ago 20
PHP Question

character to alphabet numerical value

Ok so I want to find the numerical value of a character from the alphabet. So a =1, b =2 ..z =26. Below I just called the string password, and I run a

for
loop to set a password array to equal the in the string, so password[1]= a, but because I want the user to enter the string, it could be password[1] = z. anyway, then I run another loop that has a
switch
statement to see if what character it equals to, once the
switch
statement finds that character, it sets the password array to whatever alphabet numerical value is. For some reason, the ending code is 1 1 1 1 2 2 3 3, So for some reason its off by 1 value. IDK how this is happening. Can someone help

<?php
$password = "aabbccdd";
$password_length = strlen($password);
$password_array = array($password_length);
$letter= array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');

for ($counter = 0; $counter < $password_length; $counter++) {
$password_array[$counter] = $password{$counter};

for ($x = 0; $x < 26 ; $x++) {
switch ($password_array[$counter]) {
case strtolower($letter[$x]):
$password_array[$counter] = $x;
break;
}
}
echo $password_array[$counter];
}
?>

Answer

You should compare the value of $letter[$x] with $password{$counter} instead of $password_array[$counter]. Don't forget to add $x by 1 since array index begins with 0.

$password = "aabbccdd" ;
$password_length = strlen($password);
$password_array = array($password_length); 
$letter= array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');

for($counter = 0; $counter < $password_length; $counter++ ) {
    for($x = 0; $x < 26 ; $x++ ){
        switch ($password{$counter}) {
            case strtolower($letter[$x]):
                $password_array[$counter] = $x + 1;
                break ; 
        }
    }
    echo $password_array[$counter] ; 
}

Output

11223344

Working demo: http://codepad.org/7PT4Z9t3

Alternative Solution

Your code can be simplified by changing $letter to an associative array where each letter would be the key and its numerical value would be the corresponding value. For example, $letter['a'] would be 1, $letter['b'] would be 2, and so on. Moreover, you only need one for loop. See the code below

$password = "Aabbccdd" ;
$password_length = strlen($password);
$password_array = array($password_length); 
$letter = array(
 'a'=>1, 'b'=>2, 'c'=>3, 'd'=>4, 'e'=>5,'f'=>6,'g'=>7,'h'=>8,'i'=>9,'j'=>10,
 'k'=>11,'l'=>12,'m'=>13,'n'=>14,'o'=>15,'p'=>16,'q'=>17,'r'=>18,'s'=>19,'t'=>20,
 'u'=>21,'v'=>22,'w'=>23,'x'=>24,'y'=>25,'z'=>26);

for($counter = 0; $counter < $password_length; $counter++ ) {
    $password_array[$counter] = $letter[strtolower($password{$counter})];
    echo $password_array[$counter] ; 
}

Output

11223344

Working demo: http://codepad.org/E5BgR5Lb

Comments