Results 1 to 6 of 6

Thread: ! symbol in a if statement

  1. #1
    Join Date
    Jan 2008
    Posts
    441
    Thanks
    67
    Thanked 4 Times in 4 Posts

    Default ! symbol in a if statement

    i recently cam across this statement and was slightly confused. i always thought that the ! sign means NOT, as in
    if ($i != 0) then ...
    but in the case below why would the !isLoggedIn() call the function in otherFile.php?

    Code:
    include ('otherFile.php');
    if(!isLoggedIn()) {
    	// function here
    }else{
    	// function here
    }
    otherFile.php
    Code:
    function isLoggedIn(){
    	echo '1';
    }
    Last edited by ggalan; 06-26-2011 at 12:31 AM.

  2. #2
    Join Date
    Apr 2008
    Location
    So.Cal
    Posts
    3,643
    Thanks
    63
    Thanked 516 Times in 502 Posts
    Blog Entries
    5

    Default

    because you're comparing the return value of the function. if(!somefunction()) means "If the function returns false, 0, null, or does not return anything." So, if your function returned "TRUE", then your else{} block would execute.

  3. The Following User Says Thank You to traq For This Useful Post:

    ggalan (06-26-2011)

  4. #3
    Join Date
    Jan 2008
    Posts
    441
    Thanks
    67
    Thanked 4 Times in 4 Posts

    Default

    this will echo 0

    Code:
    if(isLoggedIn()) {
    	echo '1';
    }else{
    	echo '0';
    }

  5. #4
    Join Date
    Apr 2008
    Location
    So.Cal
    Posts
    3,643
    Thanks
    63
    Thanked 516 Times in 502 Posts
    Blog Entries
    5

    Default

    PHP Code:
    function isLoggedIn(){ echo '1'; }

    if(
    isLoggedIn()){ echo '1'; }
    else{ echo 
    '0'; } 
    the function will print "1". after the function is finished, the if...else statement will print "0".


    [...aside...]

    I assume that this is only an example, and that you know that the above code, "as-is," is completely pointless: you will always get "10".

    A more practical implementation would be:
    PHP Code:
    function isLoggedIn(){
       if(
    /* user is logged in */){ return TRUE; }
       else{ return 
    FALSE; }
    }

    if(
    isLoggedIn() === TRUE){ print '1'; }
    else{ print 
    '0'; } 
    Last edited by traq; 06-25-2011 at 11:45 PM.

  6. #5
    Join Date
    Jan 2008
    Posts
    441
    Thanks
    67
    Thanked 4 Times in 4 Posts

    Default

    i should have paid more attention to your bold return
    you're comparing the return value of the function

  7. #6
    Join Date
    Apr 2008
    Location
    So.Cal
    Posts
    3,643
    Thanks
    63
    Thanked 516 Times in 502 Posts
    Blog Entries
    5

    Default

    right - your original function echoed text, but it returned nothing at all. Sorry for not being more clear!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •