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');
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.
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.
Is there any built-in PHP function through which I can count the sum of indexes of letters of the alphabet found in a string?
<?php
$a = "testword";
echo "Count of Characters is: " . strlen($a);
?>
Now I want to get a cumulative "total" of this word.
e.g.
A is the first letter of the alphabet so it maps to 1
B is the second letter of the alphabet so it maps to 2
C is the third letter of the alphabet so it maps to 3
D is the fourth letter of the alphabet so it maps to 4
So the word ABCD gives 1+2+3+4=10
Similarly I need a function for "testword" or any word.
function WordSum($word)
{
$cnt = 0;
$word = strtoupper(trim($word));
$len = strlen($word);
for($i = 0; $i < $len; $i++)
{
$cnt += ord($word[$i]) - 64;
}
return $cnt;
}
var_dump(WordSum("testword"));
Just to show a totally different method, for the sheer pleasure of demonstrating some of PHP's array functions:
$data = "testword";
$testResult = array_values(array_merge(array_fill_keys(range('A','Z'),
0
),
array_count_values(str_split(strtoupper($data)
)
)
)
);
$wordCount = 0;
foreach($testResult as $letterValue => $letterCount) {
$wordCount += ++$letterValue * $letterCount;
}
var_dump($wordCount);
$a = "test";
$b = "word";
echo (strlen($a) + strlen($b));
I am trying to write a function that will replace characters in a string with their HTML entity encoded equivalent.
I want it to be able to go through all the possible combinations for the given string, for example:
go one-by-one
then combo i.e.. 2 at a time, then three at a time, till you get length at a time
then start in combo split, i.e.. first and last, then first and second to last
then first and last two, fist and second/third last
So for the characters "abcd" it would return:
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
etc.......... so on and so forth till there are no other combinations
Any ideas, or has anyone seen a function somewhere I could modify for this purpose?
loop from 0 to 2^length - 1. On each step, if Nth bit of the loop counter is 1, encode the Nth character
$str = 'abcd';
$len = strlen($str);
for($i = 0; $i < 1 << $len; $i++) {
$p = '';
for($j = 0; $j < $len; $j++)
$p .= ($i & 1 << $j) ? '&#' . ord($str[$j]) . ';' : $str[$j];
echo $p, "\n";
}
There are 2^n combinations, so this will get huge fast. This solution will only work as long as it fits into PHP's integer size. But really who cares? A string that big will print so many results you'll spend your entire life looking at them.
<?php
$input = 'abcd';
$len = strlen($input);
$stop = pow(2, $len);
for ($i = 0; $i < $stop; ++$i)
{
for ($m = 1, $j = 0; $j < $len; ++$j, $m <<= 1)
{
echo ($i & $m) ? '&#'.ord($input[$j]).';' : $input[$j];
}
echo "\n";
}
How about this?
<?php
function permutations($str, $n = 0, $prefix = "") {
if ($n == strlen($str)) {
echo "$prefix\n";
return;
}
permutations($str, $n + 1, $prefix . $str[$n]);
permutations($str, $n + 1, $prefix . '&#' . ord($str[$n]) . ';');
}
permutations("abcd");
?>