I have the following code:
$days = 0;
$daysLastChar = mb_substr($days, -1);
switch ($daysLastChar) {
case in_array($daysLastChar, Array("1")): {
$correctDaysForm = "день";
break;
}
case in_array($daysLastChar, Array("2", "3", "4")): {
$correctDaysForm = "дня";
break;
}
case in_array($daysLastChar, Array("5", "6", "7", "8", "9", "0")): {
$correctDaysForm = "дней";
break;
}
}
The first case boolean in_array($daysLastChar, Array("1"))
expression evaluates to FALSE
and yet the flow enters this case and sets $correctDaysForm
variable to incorrect first value. Why so? It doesn't happen if the number of days ends with number other than zero.
This is not how you use a switch
statement. switch
matches the value passed in ($daysLastChar
) with the values of each of the case statements.
So, it is trying to do $daysLastChar == in_array($daysLastChar, Array("1"))
(and so on). in_array
returns a boolean, and $daysLastChar
(I assume) is a int. So, as you can see it won't match the statement that you expect it to.
switch
uses "loose comparison" (meaning it uses ==
instead of ===
). So if $daysLastChar
is 0
, then it will match the first case because in_array
returns false
, which has the same value as 0
.
One method of doing this is to use switch(true)
. So that it will compare true
with each statement to see which matches. Or, you can convert this to an if
/else
.
you are switching on $daysLastChar
. therefore if in_array($daysLastChar, Array("1"))
evaluates to $daysLastChar
then that case is executed.