Why doesn't this code simply print letters A to Z? - php

<?php
for ($i = 'a'; $i <= 'z'; $i++)
echo "$i\n";
This snippet gives the following output (newlines are replaced by spaces):
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 ap aq ar as at au av aw ax ay az ba bb bc bd be bf bg bh bi bj bk bl bm bn bo bp bq br bs bt bu bv bw bx by bz ca cb cc cd ce cf cg ch ci cj ck cl cm cn co cp cq cr cs ct cu cv cw cx cy cz da db dc dd de df dg dh di dj dk dl dm dn do dp dq dr ds dt du dv dw dx dy dz ea eb ec ed ee ef eg eh ei ej ek el em en eo ep eq er es et eu ev ew ex... on to yz

From the docs:
PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's.
For example, in Perl 'Z'+1 turns into 'AA', while in C 'Z'+1 turns into '[' ( ord('Z') == 90, ord('[') == 91 ).
Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.
From Comments:-
It should also be noted that <= is a lexicographical comparison, so 'z'+1 ≤ 'z'. (Since 'z'+1 = 'aa' ≤ 'z'. But 'za' ≤ 'z' is the first time the comparison is false.) Breaking when $i == 'z' would work, for instance.
Example here.

Because once 'z' is reached (and this is a valid result within your range, the $i++ increments it to the next value in sequence), the next value will be 'aa'; and alphabetically, 'aa' is < 'z', so the comparison is never met
for ($i = 'a'; $i != 'aa'; $i++)
echo "$i\n";

Others answers explain the observed behavior of the posted code. Here is one way to do what you want (and it's cleaner code, IMO):
foreach (range('a', 'z') as $i)
echo "$i\n";
In response to ShreevatsaR's comment/question about the range function: Yes, it produces the "right endpoint", i.e. the values passed to the function are in the range. To illustrate, the output from the above code was:
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

Others already said why PHP doesn't show what you expect. Here's how you get the result you might want:
<?php
for ($i = ord('a'); $i <= ord('z'); $i++)
echo chr($i);
?>

Why not just use range('a','z')?

Try this code. I think this code will be helpful to you.
$alphas = range('A', 'Z');
foreach($alphas as $value){
echo $value."<br>";
}
Display 26 letters in sequence.

<?php
$i = 'a';
do {
echo ($j=$i++),"\r\n";
} while (ord($j) < ord($i));
?>

Also this can be used:
for ($i = 'a'; $i <= 'z'; $i=chr(ord($i)+1))
echo "$i\n";

PHP has the function of looping letters and can exceed beyond single characters; the rest will be done this way: aa ab ac... zz, and so on.
Try this:
<?php
for ($i = 'a'; $i !== 'aa'; $i++)
echo "$i\n";
?>

While the above answers are insightful to what's going on, and pretty interesting (I didn't know it would behave like this, and its good to see why.
The easiest fix (although perhaps not the most meaningful) would be just to change the condition to $i != 'z'
<?php
for ($i = 'a'; $i != 'z'; $i++)
echo "$i\n";
?>

The PHP does not consider 'AA' less than 'Z'.
The best way to make this is:
for($i = 'a'; $i != 'aa'; $i++) {
echo $i;
}
abcdefghijklmnopqrstuvwxyz

Perhaps this code will work. It’s easy & can be understood:
<?php
$ascii_val = ord("a");
for($i=$ascii_val;$i<$ascii_val+26;$i++){
echo chr($i)."\n";
}
?>
where 26 is the total number of letters in the alphabet.

There are several ways to do that.
1. First you can take the range from 'a' to 'z'. Then iterate a loop over it.
foreach(range('a', 'z') as $i)
{
echo $i . "\n";
}
2. You can print the letters using asci value of the characters.
for($i = 97 ; $i<=122; $i++)
{
echo chr($i) . "\n";
}
3. You can take the asci value of 'a' and run a loop till the asci value of 'z':
for ($x = ord('a'); $x <= ord('z'); $x++)
{
echo chr($x) . "\n";
}
4. For printing a new line in html you can append the to the end of each characters.
for($i='a';$i<='z';$i++)
{
echo $i. "<br />";
}

this code will work. It’s easy & can be understood:
<?php
// print form A to ZZ like this
// A B C ... AA AB AC ... ZA .. ZZ
$pre = "";
$i = ord('a');
for ($x = ord('a'); $pre . strtoupper(chr($x-1)) != 'AH'; $x++)
{
echo "". $pre . strtoupper(chr($x)) . "\n";
if(chr($x) === "z"){
$pre = strtoupper(chr($i++));
$x = ord('a');
$x--;
}
}

One more way to get the display of characters a-z:
<?php
for ($i = 'a'; $i < 'z'; $i++){
echo "$i\n";
}
echo $i; // 'z'
See live code
Once the conditional loop becomes false, $i will have already been incremented and have the string value corresponding to 'z' which can be displayed.

Wow I really didn't know about this but its not a big code you can try echo "z" after loop Mark is Absolutely Right I use his method but if you want alternative then this may also you can try
<?php
for ($i = "a"; $i = "y"; $i++) {
echo "$i\n";
if ($i == "z") {}
}
echo "z";
?>

Related

Why this unexpected behavior in pushing letters [a-z] in PHP? [duplicate]

<?php
for ($i = 'a'; $i <= 'z'; $i++)
echo "$i\n";
This snippet gives the following output (newlines are replaced by spaces):
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 ap aq ar as at au av aw ax ay az ba bb bc bd be bf bg bh bi bj bk bl bm bn bo bp bq br bs bt bu bv bw bx by bz ca cb cc cd ce cf cg ch ci cj ck cl cm cn co cp cq cr cs ct cu cv cw cx cy cz da db dc dd de df dg dh di dj dk dl dm dn do dp dq dr ds dt du dv dw dx dy dz ea eb ec ed ee ef eg eh ei ej ek el em en eo ep eq er es et eu ev ew ex... on to yz
From the docs:
PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's.
For example, in Perl 'Z'+1 turns into 'AA', while in C 'Z'+1 turns into '[' ( ord('Z') == 90, ord('[') == 91 ).
Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.
From Comments:-
It should also be noted that <= is a lexicographical comparison, so 'z'+1 ≤ 'z'. (Since 'z'+1 = 'aa' ≤ 'z'. But 'za' ≤ 'z' is the first time the comparison is false.) Breaking when $i == 'z' would work, for instance.
Example here.
Because once 'z' is reached (and this is a valid result within your range, the $i++ increments it to the next value in sequence), the next value will be 'aa'; and alphabetically, 'aa' is < 'z', so the comparison is never met
for ($i = 'a'; $i != 'aa'; $i++)
echo "$i\n";
Others answers explain the observed behavior of the posted code. Here is one way to do what you want (and it's cleaner code, IMO):
foreach (range('a', 'z') as $i)
echo "$i\n";
In response to ShreevatsaR's comment/question about the range function: Yes, it produces the "right endpoint", i.e. the values passed to the function are in the range. To illustrate, the output from the above code was:
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
Others already said why PHP doesn't show what you expect. Here's how you get the result you might want:
<?php
for ($i = ord('a'); $i <= ord('z'); $i++)
echo chr($i);
?>
Why not just use range('a','z')?
Try this code. I think this code will be helpful to you.
$alphas = range('A', 'Z');
foreach($alphas as $value){
echo $value."<br>";
}
Display 26 letters in sequence.
<?php
$i = 'a';
do {
echo ($j=$i++),"\r\n";
} while (ord($j) < ord($i));
?>
Also this can be used:
for ($i = 'a'; $i <= 'z'; $i=chr(ord($i)+1))
echo "$i\n";
PHP has the function of looping letters and can exceed beyond single characters; the rest will be done this way: aa ab ac... zz, and so on.
Try this:
<?php
for ($i = 'a'; $i !== 'aa'; $i++)
echo "$i\n";
?>
While the above answers are insightful to what's going on, and pretty interesting (I didn't know it would behave like this, and its good to see why.
The easiest fix (although perhaps not the most meaningful) would be just to change the condition to $i != 'z'
<?php
for ($i = 'a'; $i != 'z'; $i++)
echo "$i\n";
?>
The PHP does not consider 'AA' less than 'Z'.
The best way to make this is:
for($i = 'a'; $i != 'aa'; $i++) {
echo $i;
}
abcdefghijklmnopqrstuvwxyz
Perhaps this code will work. It’s easy & can be understood:
<?php
$ascii_val = ord("a");
for($i=$ascii_val;$i<$ascii_val+26;$i++){
echo chr($i)."\n";
}
?>
where 26 is the total number of letters in the alphabet.
There are several ways to do that.
1. First you can take the range from 'a' to 'z'. Then iterate a loop over it.
foreach(range('a', 'z') as $i)
{
echo $i . "\n";
}
2. You can print the letters using asci value of the characters.
for($i = 97 ; $i<=122; $i++)
{
echo chr($i) . "\n";
}
3. You can take the asci value of 'a' and run a loop till the asci value of 'z':
for ($x = ord('a'); $x <= ord('z'); $x++)
{
echo chr($x) . "\n";
}
4. For printing a new line in html you can append the to the end of each characters.
for($i='a';$i<='z';$i++)
{
echo $i. "<br />";
}
this code will work. It’s easy & can be understood:
<?php
// print form A to ZZ like this
// A B C ... AA AB AC ... ZA .. ZZ
$pre = "";
$i = ord('a');
for ($x = ord('a'); $pre . strtoupper(chr($x-1)) != 'AH'; $x++)
{
echo "". $pre . strtoupper(chr($x)) . "\n";
if(chr($x) === "z"){
$pre = strtoupper(chr($i++));
$x = ord('a');
$x--;
}
}
One more way to get the display of characters a-z:
<?php
for ($i = 'a'; $i < 'z'; $i++){
echo "$i\n";
}
echo $i; // 'z'
See live code
Once the conditional loop becomes false, $i will have already been incremented and have the string value corresponding to 'z' which can be displayed.
Wow I really didn't know about this but its not a big code you can try echo "z" after loop Mark is Absolutely Right I use his method but if you want alternative then this may also you can try
<?php
for ($i = "a"; $i = "y"; $i++) {
echo "$i\n";
if ($i == "z") {}
}
echo "z";
?>

How to print letters from A-Z in a for loop?

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

Get all the palindromes in a string

I was asked to write a program in php where all the occurrences of palindromes in a given string need to be printed.
Example: For the string I O M K I L O L I K T C J I O P L L P O
The answer would be:
O P L L P O and
K I L O L I K
While doing this it should kept in mind that every palindrome that is more than 3 characters in length can be broken down into more palindromes but you just need to print out the longest size possible for each set (so, for the example string, you SHOULD NOT print LOL, LL , PLLP and ILOLI)
I tried it but could only manage to do this:
$data = 'I O M K I L O L I K T C J I O P L L P O';
$data = str_replace(' ', '', $data);
$palindromes = [];
for($i=0; $i<strlen($data); $i++ ) {
for($j=3; $j<=(strlen($data)-$i); $j++){
$word = substr($data, $i, $j);
$reverse_word = strrev($word);
if($word == $reverse_word){
print "Word: ".$word."<br/>";
}
}
}
Which gives me the following output:
Word: KILOLIK
Word: ILOLI
Word: LOL
Word: OPLLPO
Word: PLLP
Which is not the expected ouput. What should I to get rid of the strings like ILOLI, LOL PLLP because I am expected to get the longest palindrome.
According your example, you mention the answer would be O P L L P O (six characters long) and K I L O L I K (seven characters long), but later you imply only the longest palindrome should be returned?
Assuming you mean the later case, you can first assign all the palindromes to array and then sort the array, like this:
function str_length_sort($first, $second) {
return strlen($second) - strlen($first);
}
$data = 'I O M K I L O L I K T C J I O P L L P O';
$data = str_replace(' ', '', $data);
$palindromes = [];
for($i=0; $i<strlen($data); $i++ ) {
for($j=3; $j<=(strlen($data)-$i); $j++){
$word = substr($data, $i, $j);
$reverse_word = strrev($word);
if($word == $reverse_word){
$palindromes[] = $word;
}
}
}
usort($palindromes, 'str_length_sort');
$max = strlen($palindromes[0]);
foreach ($palindromes as $p) {
$length = strlen($p);
if ($length >= $max) {
echo $p;
}
}
Hope this helps.

How to find contiguous words in array

ok, this is driving me insane, the solution must be easy but I've hit the proverbial wall,
here it is:
suppose I have this Array: a, b, c, d
I want to find all the contiguous letters in the array without mixing them, such as:
a b c d
a b c
a b
b c d
b c
c d
I've done many tests, but for some reason I just can't get it right. Any hint would be greatly appreciated.
$arr = Array('a', 'b', 'c', 'd');
for ($i = 0; $i < count($arr); $i++) {
$s = '';
for ($j = $i; $j < count($arr); $j++) {
$s = $s . $arr[$j];
if (strlen($s) > 1) {
echo $s.' ';
}
}
}
OUTPUT:
ab abc abcd bc bcd cd

Auto-generate/loop a specific unordered list in PHP

I want to make something like this:
A1
B1
C1
D1
D2
D3
C2
C3
B2
C4
D10
D11
D12
C5
C6
B3
C7
C8
C9
D25
D26
D27
So it's always groups of three, with every level ascending by a letter. First level is A, second B, C, D, E and so forth. The numbers are also listed in ascending order. Level A can only reach 1, B has 3, C has 9, D has 27, and so forth.
This is really easy to generate manually, converting the letters to their ASCII equivalent, adding one and converting them to character equivalent again. Problem is, I have to loop it till S, for instance, and my mind is getting messier and messier trying to put loops within loops.
What I got (toLetter and toNumber literally does what they do):
echo "<ul><li>";
echo "A1";
echo "<ul><li>";
$b = toNumber(A);
$b++;
$b = toLetter($b);
$bnum = 1 - 1;
$bnum = $bnum * 3;
$bnum++;
echo $b;
echo $bnum."</li>";
$bnum++;
echo "<li>".$b;
echo $bnum."</li>";
$bnum++;
echo "<li>".$b;
echo $bnum."</li>";
Making this:
A1
B1
B2
B3
I really can't figure out how to just loop everything so it can reach till Z.
A pretty simple version which only goes up to the 'C' level; increase as necessary.
<?php
function outputListItems($char) {
static $index = array('A' => 1);
if (!isset($index[$char])) {
$index[$char] = 1;
}
for ($i = 0; $i < 3; $i++) {
echo '<li>';
echo $char;
echo $index[$char]++;
if ($char < 'C') {
echo '<ul>';
$nextChar = $char;
outputListItems(++$nextChar);
echo '</ul>';
}
echo '</li>';
}
}
?>
<ul>
<li>
A1
<ul><?php outputListItems('B'); ?></ul>
</li>
</ul>
A is treated as special chase, since it only has one entry.
in PHP, you can use ++ on a string, so you don't need to Letter/toNumber
And to support unlimited nesting, you need a recursion (or at least it will be easier for you)

Categories