2

I know that if statement gives a result as a Boolean.

     <?php 
            if (isset($_GET['subj'])) {
            $sel_subj = $_GET['subj'];
            $sel_page = "";
     ?>

Can i use $sel_subj or $sel_page outside if statement ? The second question in the case of while loop ? Can i use a variable outside it or its considered as in the local scope ?

while ($page = mysql_fetch_array($page_set)) {
                echo "<li";
                if ($page["id"] == $sel_page) { echo " class=\"selected\""; }
                echo "><a href=\"content.php?page=" . urlencode($page["id"]) .
                "\">{$page["menu_name"]}</a></li>";
        }

1 Answer 1

2

Basically yes, any variables defined inside an if or while will be available in the scope that the if or while exists in (as they are defined in a conditional though they might not have been set so you would receive an undefined warning)

so

    function foo(){
        $i=0
        while($i==0){
           $i=1;
           $a=1;
        }

        echo $a;
        //$a is available here although it might be undefined as the condition may not have been met

    }
    echo $a //$a is not available here

You should ideally declare the variable first.

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

2 Comments

i am sorry i make some changes on what i wrote so.. i think your answer now will be different
No it's basically the same, unlike say Java where a variable declared within a while loop (or if branch) is only available within that branch in php its available within the scope that the which (or if) has.

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.