Always remember about variable type
Yes, I use the correct word. Always remember about variable type. It is not always important because PHP uses type casting, but it may lead you to hard-to-find mistakes. For example, I need to get some variable value. There are only three allowed states: 0, basic, advanced. As you may see, 0 is easily recognizable as integer and two others are strings. If variable (it is post_meta to be exact) is not set, it should use default value – 0. So, it is pretty easy:
1 2 3 4 |
$use = get_post_meta( $post_id, 'my_value_use', true ); if ( '' == $use ) { $use = 0; } |
I do not need to filter it more, because I translate this variable once more later. So, let’s jump to this ‘later’:
1 2 3 4 5 6 7 |
$x_active = 'false'; if ( $use == 'basic' ) { $x_active = 0; } if ( $use == 'advanced' ) { $x_active = 1; } |
Yes, it isn’t a mistake. 0 has to transfer into ‘false’, basic into 0 and advanced into 1. So, this should work, shouldn’t it? Let’s trace it:
1. Set $x_active
to ‘false’ string.
2. If $use
is equal to ‘basic’, set $x_active
to 0
3. If $use
is equal to ‘advanced’, set $x_active
to 1.
Looks pretty obvious but it is wrong. Why? Because if $use is equal 0 we will always will get 1 as
$x_active
and correct value is ‘false’. Why is that? Because type casting. PHP will cast “basic” into integer (because $use is integer) and will compare those two values. If $use is integer zero and ‘basic’ after conversion is zero, too… then it is equal. So, why we’ve got 1? Because ‘advanced’ is also 0 after conversion to integer.
So, what should we do?
Pretty easy, use value and type comparison, like that:
1 2 3 4 5 6 7 |
$x_active = 'false'; if ( $x['use'] === 'basic' ) { $x_active = 0; } if ( $x['use'] === 'advanced' ) { $x_active = 1; } |
Now it works perfectly well and as expected.