TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Tips & Tricks (http://www.talkphp.com/tips-tricks/)
-   -   Toggling true/false variables (http://www.talkphp.com/tips-tricks/2473-toggling-true-false-variables.html)

Alan @ CIT 03-13-2008 10:43 PM

Toggling true/false variables
 
Hi all,

Just a quick tip for you all :-)

I'm sure that we've all used something like the following before to toggle a bool variable:

PHP Code:

if ($myVar == true)
{
    
$myVar false;
}
else
{
    
$myVar true;


Well you'll be please to know that there is a shorter way of doing it :-)

PHP Code:

$myVar ^= true

This does exactly the same as our if() block above - if $myVar is false, it sets it to true. If it is true, it sets it to false.

Hopefully usefull to someone :-)

Alan

wGEric 03-13-2008 11:56 PM

I haven't tried this but it seems like the following would work as well. It's a little easier to understand.

PHP Code:

$var = !$var


DeMo 03-14-2008 12:06 AM

I've always done it the way Eric showed. ;-)

Salathe 03-14-2008 12:23 AM

What you're doing there is utilizing the bitwise 'xor' operator. It's a little bit in depth to explain this operation in detail so we'll go with "it just works"... sort of. Since we're only working with one bit (0 or 1) the expression works something like:
PHP Code:

$myVar FALSE// (bool) false
$myVar ^= TRUE// (int) 1
$myVar ^= TRUE// (int) 0
$myVar ^= TRUE// (int) 1 

So, really we're making FALSE into (int) 1, or TRUE into (int) 0 rather than strictly converting between TRUE/FALSE. An alternative (which actually preserves boolean type) would be to go along the lines of:

PHP Code:

$myVar FALSE;   // (bool) false
$myVar = !$myVar// (bool) true
$myVar = !$myVar// (bool) false
$myVar = !$myVar// (bool) true 

As mentioned above, it keeps the boolean type rather than giving integer results and is also, for me at least, more logical (pardon the pun) in that we're saying (if $myVar is originally true) "$myVar equals not $myVar" => "$myVar equals not true" => "$myVar equals false".

NINTHTJ 07-19-2011 10:15 AM

This is the method I usually use:

Code:

$var = ($var) ? false : true;
pretty quick and easy.

maeltar 07-20-2011 06:28 AM

Handy to know, but why are you replying to a thread that is over 3 years old !

NINTHTJ 07-20-2011 08:46 AM

Oops... I don't look at post dates that much XD


All times are GMT. The time now is 01:34 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0