blablabla
blablabla

Reputation: 33

PHP variable scope and IFs

I have roughtly something similar to this:

function get_gender ($gid){ 
    $return= '';

...some code ..

    if ($male !== 0 && $female !== 0){
        $return = 'mixed';
    }else if ($male !== 0 && $female == 0){
        $return = 'male';
    }
    return $return;

}

I know for a fact that one of the condition is met, so i assumed the $return variable would be updated. Though it always comes back empty. Is this a problem of scope ?

Upvotes: 2

Views: 122

Answers (4)

oezi
oezi

Reputation: 51797

nope, this isn't a scope-problem. your variables must be set wrong, so the conditions arn't met. maybe thats because the result should be a female (i can't see an option for that), or it's because you're using explicit type-sensitive conditions(maybe your variables contain strings ander - try to make === to == and !== to == and see if something changes)

to proof this, try to add another else{ } and set $return to "oh noez" (or something else).

Upvotes: 0

Jason McCreary
Jason McCreary

Reputation: 72971

No scope should not be a problem here.

More than likely your problem lies in your conditions. Particularly the use of strict equality (i.e. !==).

Upvotes: 1

CodeCaster
CodeCaster

Reputation: 151586

No, it's a debugging problem. Scope has nothing to do here since it doesn't change (at least not in the code you provided).

Try this:

if ($male !== 0 && $female !== 0){
    $return = 'mixed';
    echo 'Return: ' . $return;
}else if ($male !== 0 && $female == 0){
    $return = 'male';
    echo 'Return: ' . $return;
} else {
    echo 'None of the conditions met';
}

Besides, don't you want booleans for this (true, false) instead of explicit integer checking?

Upvotes: 1

Ned Batchelder
Ned Batchelder

Reputation: 375574

In your code, if $male is zero, $female is never checked, and neither assignment is run, leaving $return empty.

Upvotes: 4

Related Questions