I was trying to loop though a-z with a do while loop.
I know that I also can do that with foreach and forloop.
$char = 'a';
do {
echo $char;
$char++;
} while ($char <= 'z');
Why is that giving the output:
abcdefghijklmnopqrstuvwxyzaaabacadaeafagahaiajakalamanaoapaqarasatauavawaxayazbabbbcbdbebfbgbhbibjbkblbmbnbobpbqbrbsbtbubvbwbxbybzcacbcccdcecfcgchcicjckclcmcncocpcqcrcsctcucvcwcxcyczdadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzeaebecedeeefegeheiejekelemeneoepeqereseteuevewexeyezfafbfcfdfefffgfhfifjfkflfmfnfofpfqfrfsftfufvfwfxfyfzgagbgcgdgegfggghgigjgkglgmgngogpgqgrgsgtgugvgwgxgygzhahbhchdhehfhghhhihjhkhlhmhnhohphqhrhshthuhvhwhxhyhziaibicidieifigihiiijikiliminioipiqirisitiuiviwixiyizjajbjcjdjejfjgjhjijjjkjljmjnjojpjqjrjsjtjujvjwjxjyjzkakbkckdkekfkgkhkikjkkklkmknkokpkqkrksktkukvkwkxkykzlalblcldlelflglhliljlklllmlnlolplqlrlsltlulvlwlxlylzmambmcmdmemfmgmhmimjmkmlmmmnmompmqmrmsmtmumvmwmxmymznanbncndnenfngnhninjnknlnmnnnonpnqnrnsntnunvnwnxnynzoaobocodoeofogohoiojokolomonooopoqorosotouovowoxoyozpapbpcpdpepfpgphpipjpkplpmpnpopppqprpsptpupvpwpxpypzqaqbqcqdqeqfqgqhqiqjqkqlqmqnqoqpqqqrqsqtquqvqwqxqyqzrarbrcrdrerfrgrhrirjrkrlrmrnrorprqrrrsrtrurvrwrxryrzsasbscsdsesfsgshsisjskslsmsnsospsqsrssstsusvswsxsysztatbtctdtetftgthtitjtktltmtntotptqtrtstttutvtwtxtytzuaubucudueufuguhuiujukulumunuoupuqurusutuuuvuwuxuyuzvavbvcvdvevfvgvhvivjvkvlvmvnvovpvqvrvsvtvuvvvwvxvyvzwawbwcwdwewfwgwhwiwjwkwlwmwnwowpwqwrwswtwuwvwwwxwywzxaxbxcxdxexfxgxhxixjxkxlxmxnxoxpxqxrxsxtxuxvxwxxxyxzyaybycydyeyfygyhyiyjykylymynyoypyqyrysytyuyvywyxyyyz
instead of just:
abcdefghijklmnopqrstuvwxyz
From the documentation:
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.
Try something like this:
for($i = 0, $char = 'a'; $i < 26; $i++, $char++) {
echo $char;
}
Because
<?php
$char = 'z';
var_dump(++$char); //string(2) "aa"
var_dump('aa' <= 'z'); //bool(true)
var_dump('za' <= 'z'); //bool(false)
DEMO
Personally I'd just use a loop from 97 (ascii value for a) to 122 (ascii value for z):
for ($i = 97; $i <= 122; $i++) {
echo chr($i);
}
You cannot compare z with 26 or some kind of number. You need something to compare it with the number. The function ord() does it. So, you can do something like:
$char = 'a';
do {
echo $char;
$char++;
} while (ord($char) <= ord('z'));
An alternative to the above options is the code below.
<?php
$i = '0';
while($i < '26') {
echo chr(97 + $i);
$i++;
?>
<?php
foreach(range('a', 'z') as $char) {
echo "$char ";
}
Simple range view a-z.
Related
I am trying to print out alphabets from 'A' to 'Z'using for loop. What I could do is :
foreach (range('A', 'Z') as $char) {
echo $char . "\n";
}
but what I am trying to achieve is :
for($i = 'A'; $i <= 'Z'; $i++){
echo $i . "<br>";
}
The above method gives me a ridiculously long chain of alphabets.
Using,
for($i = 'A'; $i < 'Z'; $i++){ //note the change of '<=' to '<'
echo $i;
}
does give me alphabets A to Y.
When $i reaches Z, it's still <= Z, so it echoes out and increments, then tests again to see if the result of that is <= Z.... the problem is that PHP uses Perl-style character incrementing.... incrementing Z gives AA, and AA <== Z is true in an alphabetic comparison, so it continues echoing, incrementing and testing through AB, AC, to AZ, BA, BB etc.....
it's only when it reaches YZ that the next increment gives ZZ which isn't <= Z and it terminates
The solution is to avoid using a <= comparison, but to use a !== comparison, and that needs to be a comparison against the next increment from Z, ie AA, so
for($i = 'A'; $i !== 'AA'; $i++){
...
}
As uppercase alphabetical characters are following each other in the ASCII table, you can use the chr function
for ($i = 65; $i <= 90; $i++) {
echo(chr($i).' ');
}
65 is 'A' in the ASCII Table and 90 is 'Z'
For code clearness, you could either do : (using ord function)
for ($i = ord('A'); $i <= ord('Z'); $i++) {
echo(chr($i).' ');
}
You can stop loop AA. As the next element after Z is AA
for($i = 'A'; $i != 'AA'; $i++){ //note the change of '<' to '<='
echo $i."\n";
}
With simple do-while loop:
$l = "A";
do {
echo $l;
} while($l++ != "Z");
The output:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Try like below
$apl_arr = range('A', 'Z');
for($ii=0;$ii<count($apl_arr);$ii++)
echo $apl_arr[$ii],',';
exit;
may this will help you
Sorry i made a mistake in my previous answer, Please try this:
<?php
for ($i = 'A'; $i !== 'AA'; $i++)
echo "$i\n";
?>
I think you should specify the language you are trying to get this printed with. The simplest answer I can think of is in bash with the following:
for i in {A..Z}; do echo $i; done
I want to generate .txt file with following content
*.pdf.aa,*.pdf.ab,*.pdf.ac,*.pdf.ad............
*.pdf.ba,*.pdf.bb,*.pdf.bc,*.pdf.bd............
..............
..............
*.pdf.za,*.pdf.zb,*.pdf.zc,*.pdf.zd............
which is the best way to implement this ?How to increment a character like this
EDIT:
I tried below one
for($i = 'aa'; $i <= 'z'; $i++)
{ echo "$i ";}
Here its print upto yz only not printing za,zb ...
aa ab ac.......... yu yv yw yx yy yz
You can incerement characters but you can do it with range()
$letters = range('a', 'z');
foreach($letters as $l) {
foreach($letters as $l2) {
echo $l.$l2.PHP_EOL;
}
}
Working fiddle
The other option based on #gbestard suggestion
for($a = 'aa' ; $a <= 'zz' && strlen($a) < 3 ; ++$a) {
echo $a.PHP_EOL;
}
Fiddle for second option
Change your for to:
for ($i = 'aa'; strlen($i) <= 2; $i++) {
echo $i;
}
for some reason neither $i <= 'zz' or $i < 'aaa' works, so just check the length of the string.
Hie guys i want to create a random string of numbers where there is a fixed letter B at the beginning and a set of eight integers ending with any random letter, like for example B07224081A where A and the other numbers are random. This string should be unique. How can I do this?
Do you mean something like this?
$letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$numbers = rand(10000000, 99999999);
$prefix = "B";
$sufix = $letters[rand(0, 25)];
$string = $prefix . $numbers . $sufix;
echo $string; // printed "B74099731P" in my case
The more characters - the greater chance to generate unique string.
I think that's much better method to use uniqid() since it's based on miliseconds. Uniqueness of generated string is guaranteed.
This should work for you.
$randomString = "B";
for ($i = 0; $i < 9; $i++) {
if ($i < 8) {
$randomString.=rand(0,9);
}
if ($i == 8) {
$randomString.=chr(rand(65,90));
}
}
echo $randomString;
i need to do a simple loop in php to get char from a to z.. something like:
for($i=0;$i<aNumber;$i++)
echo "char = ".intToChar($i)."<br>";
where aNumber is less then 20
You can create an array of characters easily with range [docs]:
$chars = range('a', 'z');
Or if you really only want to print them:
echo implode('<br />', range('a', 'z'));
You need understand ASCII table. See in this link. Codes for A - Z is 65 - 90 and a - z is 97 - 122.
for($i = 97; $i <= 122; $i++)
echo chr($i);
I SOLVED IN THIS WAY:
$i = 0;
$char = 'a';
$aNumber = xx;
while($i<$aNumber){
echo $char."<br>";
$char++;
$i++;
}
To return character specified by ASCII code/number use chr function. Since you want to loop from 0 to 20, then you need to add 97 to $i, 97 is ASCII code for letter a:
for($i=0;$i<$aNumber;$i++)
echo "char = ".chr($i+97)."<br>"; // + 97 because it is ASCII 'a'
If you just want to loop through those letters you can do it like this:
for($i = ord('a'); $i < ord('z'); $i++)
echo "char = ".chr($i)."<br>";
Additionally if you just want to get array of those characters you can use range function:
$chars = range('a', 'z');
I found a string after reading funny things about Jon Skeet, and I guessed that it was in ROT13. Before just checking my guess, I thought I'd try and decrypt it with PHP. Here's what I had:
$string = "Vs lbh nfxrq Oehpr Fpuarvre gb qrpelcg guvf, ur'q pehfu lbhe fxhyy jvgu uvf ynhtu.";
$tokens = str_split($string);
for ($i = 1; $i <= sizeof($tokens); $i++) {
$char = $tokens[$i-1];
for ($c = 1; $c <= 13; $c++) {
$char++;
}
echo $char;
}
My string comes back as AIaf you aasakaead ABruacae Sacahnaeaiaer to adaeacrypt tahais, ahae'ad acrusah your sakualal waitah ahais alaauagah.
My logic seems quite close, but it's obviously wrong. Can you help me with it?
Try str_rot13.
http://us.php.net/manual/en/function.str-rot13.php
No need to make your own, it's built-in.
Here is a working implementation, without using the nested loop. You also don't need to split the string into an array, since you can index individual characters just like an array with strings in PHP.
You need to know that ASCII upper-case characters range from 65 - 99, and lower-case characters range from 97 - 122. If the current character is in one of those ranges, add 13 to its ASCII value. Then, you check if you should have rolled over to the beginning of the alphabet. If you should've rolled over, subtract 26.
$string = "Vs lbh nfxrq Oehpr Fpuarvre gb qrpelcg guvf, ur'q pehfu lbhe fxhyy jvgu uvf ynhtu.";
for ($i = 0, $j = strlen( $string); $i < $j; $i++)
{
// Get the ASCII character for the current character
$char = ord( $string[$i]);
// If that character is in the range A-Z or a-z, add 13 to its ASCII value
if( ($char >= 65 && $char <= 90) || ($char >= 97 && $char <= 122))
{
$char += 13;
// If we should have wrapped around the alphabet, subtract 26
if( $char > 122 || ( $char > 90 && ord( $string[$i]) <= 90))
{
$char -= 26;
}
}
echo chr( $char);
}
This produces:
If you asked Bruce Schneier to decrypt this, he'd crush your skull with his laugh.
If you want to do this yourself, instead of using an existing solution, you need to check whether each letter is at the first or second half of the alphabet. You can't naively add 13 (also, why are you using a loop to add 13?!) to each character. You must add 13 to A-M and subtract 13 from N-Z. You must also, not change any other character, like space.
Alter your code to check each character for what it is before you alter it, so you know whether and how to alter it.
This is not working because z++ is aa
$letter = "z";
$letter++;
echo($letter);
returns aa not a
EDIT: A possible alternative solution not using the built in is
$string = "Vs lbh nfxrq Oehpr Fpuarvre gb qrpelcg guvf, ur'q pehfu lbhe fxhyy jvgu uvf ynhtu.";
$tokens = str_split($string);
foreach($tokens as $char)
{
$ord = ord($char);
if (($ord >=65 && $ord <=90 ) || ($ord >= 97 && $ord <= 122))
$ord = $ord+13;
if (($ord > 90 && $ord < 110) || $ord > 122)
$ord = $ord - 26;
echo (chr($ord));
}
Just a few years late to the party, but I thought I'd give you another option to do this
function rot13($string) {
// split into array of ASCII values
$string = array_map('ord', str_split($string));
foreach ($string as $index => $char) {
if (ctype_lower($char)) {
// for lowercase subtract 97 to get character pos in alphabet
$dec = ord('a');
} elseif (ctype_upper($char)) {
// for uppercase subtract 65 to get character pos in alphabet
$dec = ord('A');
} else {
// preserve non-alphabetic chars
$string[$index] = $char;
continue;
}
// add 13 (mod 26) to the character
$string[$index] = (($char - $dec + 13) % 26) + $dec;
}
// convert back to characters and glue back together
return implode(array_map('chr', $string));
}