stack stack - 5 months ago 13
PHP Question

Why substr() doesn't work correctly with a number that has a leading zero?

I have this script:

function DecryptId($id) {
$first_digit = substr($id, 0,1);
if ( $first_digit == 0 ) {
return 'yes';
} else {
return 'no';
}
}

$id = 014;
echo DecryptId($id);

//=> no


Demo



Why it prints
no
? I expect it prints
yes
. Because the value of
$id
starts with
0
. What's wrong?




EDIT: In reality I'm passing
$id
like this:
DecryptId($_POST['au']);
.
$_POST['au']
is containing a number. Something like these:

23
43552
0153
314
09884


As you see, sometimes that number starts with
0
. And I need to pass it as a string. How can I do that?

Answer

Your function is working fine the issue is that you are passing a number in your function when you should provide a string. So in the case that your variable type is integer the leading zero will eventually fly away.

You can add something to your function to check the variable type and inform the user.

function DecryptId($id) {
    $type = gettype( $id );
    if($type!= "string") {
    echo "Your variable has type ".$type.". Use a 'string' type variable";
    return;
    }
    $first_digit = substr($id, 0,1);
    if ( $first_digit == 0 ) {
        return 'yes';
    } else {
        return 'no';
    }
}

$id = 014;
echo DecryptId($id);
echo "\n";
$id = '014';
echo DecryptId($id);

Try the above example in PHP Sandbox