Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - toggle state

Tags:

php

math

The problem is simple, but I'm looking for a creative solution. We meet very often arrays, objects that has a property that can be toggled (it can be active or inactive, 1 or 0).

What I want is a creative solution (a function) to transform 0 to 1, and 1 to 0.

Some examples:

// First
if ($state == 1)
{
  $state = 0;
}
else
{ 
  $state = 1; 
}

// Second
$states = array(1, 0);
$state = $states[$state];

// Third
$state = ($state == 1) ? 0 : 1;

Is there another, one line solution for this? Thanks, and enjoy the brainstorming.

like image 462
Tamás Pap Avatar asked May 11 '12 08:05

Tamás Pap


1 Answers

You can do:

$state = 1 - $state;
like image 163
codaddict Avatar answered Oct 04 '22 03:10

codaddict