エコーが空($ location)が印刷されていても、対応するステートメントが実行されないのはなぜですか
-
19-09-2019 - |
質問
echo empty($location);
switch($location){
case (empty($location)):
expression 1;
break;
case ($location%10000==0):
expression 2;
break;
case ($location%100==0):
expression 3;
break;
default:
expression 4;
break;
}
空のエコー($ location)、それは1を印刷します。なぜ式1が実行されないのですか?
解決
スイッチステートメントを適切に使用していません。彼らが働く方法は、各ケースの値を初期と比較することです switch
価値。
あなたの場合、ふりをしましょう $location = null
;
echo empty($location); // true: null is considered empty.
switch ($location) {
case empty($location) : // this performs the check:
// $location == empty($location)
// null == true ==> false
だからそれが実行されない理由です。
固執することをお勧めします if .. else
この場合。
他のヒント
The empty
function returns a boolean value of 1 or 0 http://uk3.php.net/empty
Whereas the switch / case
statements check whether a variable holds a certain value and execute an expression depending on that
In you case, expression 1
should be executed if the value of $location==1
(you effectively asked for that when you typed switch($location)
),
So the logic of your above code is:
if $location==1, execute expression 1
if $location%10000==0, execute expression 2
etc. etc.
is the value of $location==1
?
A switch
statement is not the same as an if/else
statement. Switch statements are looking for specific values. If it finds the value specified in a given case
statement, it runs the code after that case
statement.
The following code:
switch($x)
case 1:
// some stuff
break;
case 2:
// some other stuff
break;
default:
// some more stuff
break;
Is the equivalent of this code:
if($x == 1){
// some stuff
}
elseif($x == 2){
// some other stuff
}
else{
// some more stuff
}
Basically, switch
statements are shortcuts for if/elseif/else
blocks where you're checking for a single variable's equality against a bunch of possibilities.
Since empty()
returns 0 or 1, your first case
will run if $location
is 1 (if $location
is empty) or 0 (if $location
isn't empty). It's almost like you've written the following:
elseif($location == empty($location)){ ...
Make sense? Instead of using a switch
statement, you probably want the following:
if(empty($location)){
// ...
}
elseif($location % 10000 == 0){
// ...
}
// ...