user1418434
user1418434

Reputation: 63

Decrementing alphabetical values

I'm trying to figure out how to shift a bunch of letter values in an array down one step. For example, my array contains values ("d", "e", "f", "g", "h") and I want to change this to ("c", "d", "e", "f", "g"). Here's the code I'm working with:

function move_up_left($x) {
    if($x['orientation'] == "down") {
        foreach($x[0] as &$value) {
            $value = --$value; 
        }
    } else {
        foreach($x[1] as &$value) {
            $value = --$value;
        }
    }

    return $x;
}

When I use positive values, the letters change; however the negative numbers do not seem to be working at all.

Upvotes: 6

Views: 3587

Answers (3)

Vincent Gloaguen
Vincent Gloaguen

Reputation: 141

If you need to decrement Excel-like variables ('A', 'AA', ...), here's the function I came to. It doesn't work with special characters but is case insensitive. It returns null if you try to decrement 'a' or 'A'.

function decrementLetter($char) {
     $len = strlen($char);
     // last character is A or a
     if(ord($char[$len - 1]) === 65 || ord($char[$len - 1]) === 97){ 
          if($len === 1){ // one character left
               return null;
           }
           else{ // 'ABA'--;  => 'AAZ'; recursive call
               $char = decrementLetter(substr($char, 0, -1)).'Z';
            }
     }
     else{
         $char[$len - 1] = chr(ord($char[$len - 1]) - 1);
     }
     return $char;
}

Upvotes: 8

Rocco
Rocco

Reputation: 1085

function shift_character($array, $right = FALSE)
{
    $inc = ($right) ? 1 : -1;
    for ($i = 0; $i < count($array); $i++)
    {
        $array[$i] = chr(ord($array[$i]) + $inc);
    }
    return $array;
}

$example = array('b', 'c');
$shift_left = shift_character($example);
$shift_right = shift_character($example, TRUE);

print_r($example);
print_r($shift_left);
print_r($shift_right);

Upvotes: 0

Ry-
Ry-

Reputation: 225054

PHP has overloaded ++ for strings; this isn't the case for --. You can do the same thing with much cleaner code with chr, ord, and array_map:

function decrementLetter($l) {
    return chr(ord($l) - 1);
}

function move_up_left($x) {
    if($x['orientation'] === 'down') $arr = &$x[0];
    else $arr = &$x[1];

    $arr = array_map('decrementLetter', $arr);

    return $x;
}

Here's a demo. Note that you may need to add a special case for decrementing a - I'm not sure how you want to deal with that.

Upvotes: 16

Related Questions