2

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 ?

4
  • what is $male and $female set to? its not very clear. Commented Sep 12, 2011 at 14:01
  • If $male === 0, it will not enter either of those conditions. Do an echo inside the if else blocks to see if PHP ever gets there Commented Sep 12, 2011 at 14:02
  • Also, why don't you do an explicit return from the if-else block instead of having this $return variable? It will save you a couple of steps, a variable and IMO it's cleaner. Commented Sep 12, 2011 at 14:06
  • 1
    @NullUserException: there used to be (maybe still is) a school of thought that says a function should have only one return point, so what silkAdmin does is exactly what is recommended by this school. Commented Sep 12, 2011 at 14:13

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it was actually coming from how i was loading the variable i was checking.. Nothing to do with the code though you all made good points ! Thanks again
1

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?

Comments

1

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. !==).

Comments

0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.