phpdebuggingoutputmodular-design

my php code runs, loads, but no outputs


I was trying to create a program in which simply generates license keys. Here it is:

<?php

function gen_code_alpha()
{
    $alpha = '';

    for ($i = 0; $i <= 9; $i++) {
        $alpha .= $i;
    }

    // This attaches alphabets from 'a' to 'z' to our $alpha
    for ($i = 65; $i <= 122; $i++) {
        $alpha .= chr($i);
    }
}

function gen_code($len = 1)
{
    gen_code_alpha();
    global $alpha;

    $strlen = strlen($alpha);

    $code = '';
    for ($k = 0; $k < $len; $k++) {
        $i = $rand(0, $strlen -1);// now wanna randomly generate the code
        $code .= substr($alpha, $i, 1);
    }

    return $code;
}

function gen_license_key()
{
    $licenseKey = gen_code(4) . '-' .
                  gen_code(4) . '-' .
                  gen_code(4) . '-' .
                  gen_code(4) . '-' .
                  gen_code(2);
}

gen_license_key();
echo $licenseKey;

But when I try to run it, it doesn't show any outputs. I'm new to PHP and I don't know alot about debugging, But I had some tries. I put some echos in the code which I understood my $alpha is being successfully generated in gen_code_alpha() function. I also tried to echo $licenseKey in gen_license_key() function which didn't help. I didn't find out anything more.

So what do you think?


Solution

  • Here is the complete code working

    Notice that you have a typo (rand, not $rand)

    I also would suggest that you change the code to avoid using global variables, which is a bad practice.

    <?php
    
    function gen_code_alpha()
    {
        global $alpha;
    
        $alpha = '';
    
        for ($i = 0; $i <= 9; $i++) {
            $alpha .= $i;
        }
    
        // This attaches alphabets from 'a' to 'z' to our $alpha
        for ($i = 65; $i <= 122; $i++) {
            $alpha .= chr($i);
        }
    }
    
    function gen_code($len = 1)
    {
        gen_code_alpha();
        global $alpha;
    
        $strlen = strlen($alpha);
    
        $code = '';
        for ($k = 0; $k < $len; $k++) {
            $i = rand(0, $strlen -1);// now wanna randomly generate the code
            $code .= substr($alpha, $i, 1);
        }
    
        return $code;
    }
    
    function gen_license_key()
    {
        $licenseKey = gen_code(4) . '-' .
                    gen_code(4) . '-' .
                    gen_code(4) . '-' .
                    gen_code(4) . '-' .
                    gen_code(2);
        return $licenseKey;
    }
    
    $licenseKey = gen_license_key();
    echo "l:".$licenseKey;
    
    ?>
    

    outputs:

     l:3X6D-gnQL-I0zJ-TRQD-Sq