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++; 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.
Source: http://php.net/manual/en/language.operators.increment.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With