Why is the same code for Java and PHP not working?

I wrote a program in PHP and Java that generates all possible words of length 2. I used recursion. Why does the program work in Java, but not in PHP? This is 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);
    }
}
}
+4
source share
2 answers

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 can’t. Therefore, I will try to explain a little

In php, when you compare 2 lines, the system will try to compare the first character and then the second ..... the comparison operator will be stopped when the first different character appears

Example

$a = 'ABCDEZ';
$b = 'ABCEZZ';

String $b $a, ABC $a $b , E ( 3 $b) D ( 3 $a),

for ($c = 'A'; $c <= 'Z'; $c++) {

$c = 'Z', $++ "AA", php , "AA" < "Z" ,

foreach (range('A', 'Z') as $c){

, , , , , php,

+5

$c PHP. ++ - .

PHP Perl , C. , PHP Perl $a = 'Z'; $a++; $a 'AA', C a = 'Z'; a++; a '[' ( ASCII 'Z' 90, ASCII '[' 91), , , , ASCII (a-z, A-Z 0-9). / , .

: http://php.net/manual/en/language.operators.increment.php

+8

Source: https://habr.com/ru/post/1686938/


All Articles