Your approach is correct and will work as well. Just you need to wrap it into a function. Another way is using ^ (Bitwise XOR) to do that functional and more clean: 
function toggleNumber( $num ) {
    return $num ^= 1;
}
Online Demo
That function gets the number and does XOR with 1 on it. Then the number will be toggled.
solved How can I toggle a boolean number?