I wrote a program in PHP and Java which generates all possible words with length 2. I used recursion. Why does the program work in Java but not in PHP? It's the same code.
Java
package com.company;
public class Words {
public static void main(String[] args) {
generate("", 2);
}
static void generate(String prefix, int remainder) {
if (remainder == 0) {
System.out.println(prefix);
} else {
for (char c = 'A'; c <= 'Z'; c++) {
generate(prefix + c, remainder - 1);
}
}
}
}
PHP
generate('', 2);
function generate($prefix, $remainder)
{
if ($remainder == 0) {
echo "$prefix\n";
} else {
for ($c = 'A'; $c <= 'Z'; $c++) {
generate($prefix . $c, $remainder - 1);
}
}
}
$c
has string type in PHP. The ++
operator works differently for it compared to numbers.
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++;
$a = 'Z'; $a++;
turns $a
into 'AA'
, while in C a = 'Z'; a++;
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 (az, AZ and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.
Source: http://php.net/manual/en/language.operators.increment.php
Change your loop from
for ($c = 'A'; $c <= 'Z'; $c++) {
to
foreach (range('A', 'Z') as $c){
============================
EDIT :
Sorry, I tried to find an official document about this, but I cannot. So I'll try to explain a little
In php, when you compare 2 strings, the system wil try to compare the first character and then the second ..... the compare operator will be stop when the first different character appear
Example
$a = 'ABCDEZ';
$b = 'ABCEZZ';
String $b greater than $a because the value ABC in the beginning of $a and $b is the same but E (the value in index 3 of string $b) greater than D (the value in index 3 of string $a), and they don't need to compare other characters
In this question, the original loop is
for ($c = 'A'; $c <= 'Z'; $c++) {
it's fine until $c = 'Z', but after that $c++ will be 'AA' and when php start to compare it, 'AA' < 'Z' and the loop continue, that's why I changed the loop to
foreach (range('A', 'Z') as $c){
To make it work
I hope you enjoy it and happy with my explain, sorry because I don't see any document about this, it's just how php work and I know it
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.