SITERAW

[PHP] Switch with different types

Author Message
Posey # Posted yesterday
How to handle a switch with strict comparison Hello.

I'm trying to make the switch statement follow a strict comparison model as opposed to the default loose method (in other words, use === instead of ==) in order to make it respect data types.
<?php
switch ($value) {

case '0':
echo 'string zero';
break;

case 0:
echo 'dec zero';
break;

case '':
echo 'empty string';
break;

case null:
echo 'null';
break;

case false:
echo 'bool false';
break;

default:
echo 'default';
break;
}

?>
Obviously this code doesn't work the way I intend it to.

What are some solutions other than switching to if/else.
Ads
Taurre # Posted two hours ago
Taurre Bare in mind that you're asking PHP, an interpreted high-level language, to juggle types on the fly. You're better off doing a type-check first before proceeding to the conditional loop.
Celeri # Posted one hour ago
Celeri Yeah, and he's asking precisely how to have PHP not juggle types.
switch (true) {

case $value === 0:
echo 'dec zero';
break;

case $value === '':
echo 'empty string';
break;

case $value === null:
echo 'null';
break;

case $value === false:
echo 'bool false';
break;

default:
echo 'default';
break;

}
Kim Jong Un # Posted 37 minutes ago
Kim Jong Un Celeri's approach is probably the best.

Alternatively you can try basic typecasting: switch((string)$value).
Posey # Posted 5 minutes ago
Posey Thanks all, I'll try these methods.

Post a reply