Given any character from a to z, what is the most efficient way to get the 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];
}
It depends on what you want to do when you hit Z, but you have a few options:
$nextChar = chr(ord($currChar) + 1); // "a" -> "b", "z" -> "{"
You could also make use of PHP's range() function:
$chars = range('a', 'z'); // ['a', 'b', 'c', 'd', ...]
Well, it depends what exactly you want to do with the "edge cases". What result do you expect when the character is z or Z? Do you want the next letter of the same case, or just the next letter, period?
Without knowing the answer to that, for the very basic case, you can just do this:
$next_character = chr(ord($current_character) + 1);
But when you're at Z this will give you [, and z will give you {, according to ASCII values.
Edited as per comment:
If you need the next character of the same case, you can probably just add simple checks after the line above:
if ($next_character == '[')
$next_character = 'A';
else if ($next_character == '{')
$next_character = 'a';
These are very simple operations, I really wouldn't worry about efficiency in a case like this.
How about using ord() and chr()?
<?php
$next = chr(ord($prev)+1);
?>
Since I only care about lowercase characters in this case, I'll use the following code, based on the answers posted here:
function nextLetter(&$str) {
$str = ('z' === $str ? 'a' : ++$str);
}
Thanks for the help, guys!
$val = 'z';
echo chr((((ord($val) - 97) + 1) % 26) + 97);
Nice and easy :-)
Create an array of all letters, search for existing letter and return its next letter. If you reach the last letter return first letter.
Related
Given any character from a to z, what is the most efficient way to get the 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];
}
It depends on what you want to do when you hit Z, but you have a few options:
$nextChar = chr(ord($currChar) + 1); // "a" -> "b", "z" -> "{"
You could also make use of PHP's range() function:
$chars = range('a', 'z'); // ['a', 'b', 'c', 'd', ...]
Well, it depends what exactly you want to do with the "edge cases". What result do you expect when the character is z or Z? Do you want the next letter of the same case, or just the next letter, period?
Without knowing the answer to that, for the very basic case, you can just do this:
$next_character = chr(ord($current_character) + 1);
But when you're at Z this will give you [, and z will give you {, according to ASCII values.
Edited as per comment:
If you need the next character of the same case, you can probably just add simple checks after the line above:
if ($next_character == '[')
$next_character = 'A';
else if ($next_character == '{')
$next_character = 'a';
These are very simple operations, I really wouldn't worry about efficiency in a case like this.
How about using ord() and chr()?
<?php
$next = chr(ord($prev)+1);
?>
Since I only care about lowercase characters in this case, I'll use the following code, based on the answers posted here:
function nextLetter(&$str) {
$str = ('z' === $str ? 'a' : ++$str);
}
Thanks for the help, guys!
$val = 'z';
echo chr((((ord($val) - 97) + 1) % 26) + 97);
Nice and easy :-)
Create an array of all letters, search for existing letter and return its next letter. If you reach the last letter return first letter.
Hello PHP professionals,
With:
$count = 0; // start count
$count = $count +1; // addition value
i can define an automatic counter per text paragraph.
At each paragraph the value will be incremented automatically:
1st paragraph: echo $count++;. (results is 1.) text
2nd paragraph: echo $count++;. (results is 2.) text
3rd paragraph: echo $count++;. (results is 3.) text
4th paragraph: echo $count++;. (results is 4.) text
etc.
this works without errors.
Question:
How could it be achieved that not digits 1 to x are output, but alphabetically from A to Z?
Try the following:
$letter = chr($count + 65);
If you have more than 26 paragraphs use modulo
Instead of starting with 0, you can start with 'A' or "A". The increment operator in PHP works for letters as well:
PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in PHP and Perl $a = 'Z'; $a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII value of 'Z' is 90, ASCII value of '[' is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII alphabets and digits (a-z, A-Z and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.
In your case you simply write $count = 'A'; and use echo $count++; as usual.
The chr() function transfers the passed in integer into the according ACSII character.
So you can do this:
$count = 1;
echo chr(65 + $count++); // 'A' == 65
echo chr(65 + $count++);
echo chr(65 + $count++);
It work fine, and for small letters it works with:
echo chr(97 + $count++); // 'a' == 97
Thanks for help.
How can I get the first and the last digit of a number? For example 2468, I want to get the number 28. I am able to get the ones in the middle (46) but I can't do the same for the first and last digit.
For the digits in the middle I can do it
$substrmid = substr ($sum,1,-1); //my $sum is 2468
echo $substrmid;
Thank you in advance.
You can get first and last character from string as below:-
$sum = (string)2468; // type casting int to string
echo $sum[0]; // 2
echo $sum[strlen($sum)-1]; // 8
OR
$arr = str_split(2468); // convert string to an array
echo reset($arr); // 2
echo end($arr); // 8
Best way is to use substr described by Mark Baker in his comment,
$sum = 2468; // No need of type casting
echo substr($sum, 0, 1); // 2
echo substr($sum, -1); // 8
You can use substr like this:
<?php
$a = 2468;
echo substr($a, 0, 1).substr($a,-1);
You can also use something like this (without casting).
$num = 2468;
$lastDigit = abs($num % 10); // 8
However, this solution doesn't work for decimal numbers, but if you know that you'll be working with nothing else than integers, it'll work.
The abs bit is there to cover the case of negative integers.
$num = (string)123;
$first = reset($num);
$last = end($num);
What would be an elegant way of doing this?
I have this -> "MC0001" This is the input. It always begins with "MC"
The output I'd be aiming with this input is "MC0002".
So I've created a function that's supposed to return "1" after removing "MC000". I'm going to convert this into an integer later on so I could generate "MC0002" which could go up to "MC9999". To do that, I figured I'd need to loop through the string and count the zeros and so on but I think I'd be making a mess that way.
Anybody has a better idea?
This should do the trick:
<?php
$string = 'MC0001';
// extract the part succeeding 'MC':
$number_part = substr($string, 2);
// count the digits for later:
$number_digits = strlen($number_part);
// turn it into a number:
$number = (int) $number_part;
// make the next sequence:
$next = 'MC' . str_pad($number + 1, $number_digits, '0', STR_PAD_LEFT);
using filter_var might be the best solution.
echo filter_var("MC0001", FILTER_SANITIZE_NUMBER_INT)."\n";
echo filter_var("MC9999", FILTER_SANITIZE_NUMBER_INT);
will give you
0001
9999
These can be cast to int or just used as they are, as PHP will auto-convert anyway if you use them as numbers.
just use ltrim to remove any leading chars: http://php.net/manual/en/function.trim.php
$str = ltrim($str, 'MC0');
$num = intval($str);
<php
// original number to integer
sscanf( $your_string, 'MC%d', $your_number );
// pad increment to string later on
sprintf( 'MC%04u', $your_number + 1 );
Not sure if there is a better way of parsing a string as an integer when there are leading zero's.
I'd suggest doing the following:
1. Loop through the string ( beginning at location 2 since you don't need the MC part )
2. If you find a number thats bigger than 0, stop, get the substring using your current location and the length of the string minus your current location. Cast to integer, return value.
You can remove the "MC" par by doing a substring operating on the string.
$a = "MC0001";
$a = substr($a, 2); //Lengths of "MC"
$number = intval($a); //1
return intval(str_replace($input, 'MC', ''), 10);
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
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.
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
This may help you:
http://www.php.net/manual/en/function.ord.php
So, if you need the ASCII code you will need to do:
$dest = 'a';
$conv = ord($dest);
If you want something like:
a == 1
b == 2
.
.
.
you should do:
$dest = 'a';
$conv = ord($dest)-96;
For more info on the ASCII codes: http://www.asciitable.com/
And for the function ord: http://www.php.net/manual/en/function.ord.php
It's very hard to answer because it's not a real question but just a little bit of it.
But if you ask.
It seems you need some translation table, that defines links between letters and numbers
A -> 2
B -> 3
C -> 4
S -> 1
or whatever.
You can achieve this by using an array, where keys would be these letters and values - desired numbers.
$defects_arr = array(
'A' -> 2,
'B' -> 3,
'C' -> 4'
'S' -> 1
};
Thus, you can convert these letters to numbers
$letter = 'A';
$number = $defects_arr($letter);
echo $number; // outputs 1
But it still seems is not what you want.
Do these defect types have any verbose equivalents? If so, why not to use them instead of letters?
Telling the whole story instead of little bit of it will help you to avoid mistakes and will save a ton of time, both yours and those who to answer.
Out of this question, if you are looking for convert RT0005 to 5
$max = 'RT0005';
return base_convert($max,10,10);
// return 5