Most Efficient Way to Get Next Letter in the Alphabet Using PHP

Most efficient way to get next letter in the alphabet using PHP

The most efficient way of doing this in my opinion is to just increment the string variable.

$str = 'a';
echo ++$str; // prints 'b'

$str = 'z';
echo ++$str; // prints 'aa'

As seen incrementing 'z' give 'aa' if you don't want this but instead want to reset to get an 'a' you can simply check the length of the resulting string and if its >1 reset it.

$ch = 'a';
$next_ch = ++$ch;
if (strlen($next_ch) > 1) { // if you go beyond z or Z reset to a or A
$next_ch = $next_ch[0];
}

Most efficient way to get next letter in the alphabet using PHP

The most efficient way of doing this in my opinion is to just increment the string variable.

$str = 'a';
echo ++$str; // prints 'b'

$str = 'z';
echo ++$str; // prints 'aa'

As seen incrementing 'z' give 'aa' if you don't want this but instead want to reset to get an 'a' you can simply check the length of the resulting string and if its >1 reset it.

$ch = 'a';
$next_ch = ++$ch;
if (strlen($next_ch) > 1) { // if you go beyond z or Z reset to a or A
$next_ch = $next_ch[0];
}

Most efficient way to get previous letter in the alphabet using PHP

I could solve in this way.
How is it?
The cons is that it only can handle uppercase right now.
Some more work can also fix that.

<?php
function get_previous_letter($string){
$last = substr($string, -1);
$part=substr($string, 0, -1);
if(strtoupper($last)=='A'){
$l = substr($part, -1);
if($l=='A'){
return substr($part, 0, -1)."Z";
}
return $part.chr(ord($l)-1);
}else{
return $part.chr(ord($last)-1);
}
}
echo get_previous_letter("AAAAAA");
?>

CODEPAD

How to increment letters like numbers in PHP?

Character/string increment works in PHP (though decrement doesn't)

$x = 'AAZ';
$x++;
echo $x; // 'ABA'

How to increment the letter of alphabet by 2 or more instead of 1 each time?

Use php chr and php ord

$alphabet = "A";
$ascii = ord($alphabet);
$ascii += 2;
echo $alphabet = chr($ascii);

LIve demo : https://eval.in/907132

How to implement in php next char using ord() and chr()

Requirements: Allow increment of a string in the same manner as PHP (please see links in the question). At first I thought: How unusual? I still think that.

Ok, We need to produce something that will do that without using the PHP routines.

Ok, what do have?

I thought of it as a 'base26' number. I chose to implement it as:

  • using an array for each digit that had a range of 1 .. 26.
  • convert the numerical digit in the array to display characters using an array lookup.

Working demonstration at eval.in

For convenience, I put it in PHP class:

I try and make the code understandable...

The base26 class:

class base26 { // it only does increment / addition 

const
numberBase = 26;

// These are characters used where A => 1 and Z is 26
// These can be changed as you wish. They could be multibyte?

// 0 1 2 2
// 12345678901234567890123456
public static $displayChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

/**
* current number - least significant digit is digit[0]
*
* @var array $digit - integer with range 1 .. 26
*/
public $digit = array();

// initialize if nothing provided
public function __construct($letters = 'A')
{
$this->init($letters);
}

/**
* Convert letters to base26 and store in the $digit array
*
* @param string $letters
* @return void
*/
public function init($letters = 'A')
{
$this->digit = array();
$lsd = strlen($letters) - 1;

for ($idx = $lsd; $idx >= 0; $idx--) {
$this->digit[] = $this->charValue($letters[$idx]);
}
}

/**
* Increment the 'least significant digit' and then propagate the `carry`
* when it exceeds the number base limit.
*
* @param integer $int -- default to 1
* @return void
*/
public function inc($int = 1) // addition with carry - easy to understand
{
$curDigit = 0; // add to least significant digit
$carry = 0;

$this->digit[$curDigit] += $int;

while ($this->digit[$curDigit] > self::numberBase) {

$carry = 1; // next carry
$this->digit[$curDigit] %= self::numberBase; // reset digit

$curDigit++; // check next digit...

if (isset($this->digit[$curDigit])) {
$this->digit[$curDigit] += $carry;
}
else {
$this->digit[$curDigit] = $carry;
}
}
}

/**
* Convert a number to a character to display
*
* @param intger $int
*
* @return char
*/
public function toChar($int)
{
return self::$displayChars[$int - 1];
}

/**
* The value of the character in the number base range
*
* @param undefined $letter
* @return integer
*/
public function charValue($letter)
{
return stripos(self::$displayChars, $letter) + 1;
}

/**
* return the current number values as a string using the display characters
*
* @return string
*/
public function current()
{
$digitCount = count($this->digit);
$outStr = str_pad('A', count($this->digit));
$outIdx = $digitCount - 1;
for ($idx = 0; $idx < $digitCount; $idx++, $outIdx-- ) {
$outStr[$outIdx] = $this->toChar($this->digit[$idx]);
}

return $outStr;
}
}

Examples:

// ---------------------------------------------
// show increment from Z -> AA
echo PHP_EOL;
$b26 = new base26('Z');
echo $b26->current() .'|';
$b26->inc();
echo $b26->current() .'|';

Output: Z|AA|

// ---------------------------------------------
// show increment from 'FY' -> FZ -> GA
echo PHP_EOL;
$b26->init('FY');
echo $b26->current() .'|';
$b26->inc();
echo $b26->current() .'|';
$b26->inc();
echo $b26->current() .'|';

Output: FY|FZ|GA|

// ---------------------------------------------
// Show it does what PHP does...
echo PHP_EOL;
$b26 = new base26();
while ($b26->current() <= 'Z') {
echo $b26->current() .'|';
$b26->inc();
}

Output: 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|AA|AB|AC|AD|AE|AF|AG|AH|AI|AJ|AK|AL|AM|AN|AO ...

Is there a way to get the next letter in the alphabet

You can walk the ascii table:

public static void Main()
{
var letter = 'd';
Console.WriteLine((char)(letter + 1));
}

Best way to list Alphabetical(A-Z) using PHP

You can either do:

foreach (range('A', 'Z') as $char) {
echo $char . "\n";
}

Or:

for ($char = 'A'; $char <= 'Z'; $char++) {
echo $char . "\n";
}

Checking value from database and Incrementing letters

$data= "AC";
$data++;
echo $data; //AD

you should use google :)

page 1

page 2

page 3

Incrementing/Decrementing Operators

Now, to select the last value, in this case AC

$query = "SELECT code FROM table_name ORDER BY id DESC LIMIT 1";

//this should return the last record

To sum both letter

str_split

$data= "AA";
$letter= str_split($data);
$letter[0]++;
$letter[1]++;
echo $letter[0].$letter[1];

Is every letter in the alphabet in a string at least once?

With regex you can do that, but it isn't optimal nor fast at all, @hjpotter way if from far faster:

var_dump(strlen(preg_replace('~[^a-z]|(.)(?=.*\1)~i', '', $str)) == 26);

It removes all non letter characters, all duplicate letters (case insensitive), and compares the string length with 26.

  • [^a-z] matches any non letter character
  • (.) captures a letter in group 1
  • (?=.*\1) checks if the same letter is somewhere else (on the right)
  • the i modifier makes the pattern case insensitive


Related Topics



Leave a reply



Submit