Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the same code for Java and PHP not work?

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);
    }
}
}
like image 964
Umut Savas Avatar asked Dec 05 '22 13:12

Umut Savas


1 Answers

$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

like image 112
Aleh Maksimovich Avatar answered Dec 24 '22 11:12

Aleh Maksimovich