S
S
seredaes2018-02-27 12:22:25
PHP
seredaes, 2018-02-27 12:22:25

Who faced a strange bug in PHP when using switch case?

<?php

$userLang = 0;
switch($userLang) {
    case ($userLang>2):
            $userLang = 1;
            break;
}
echo $userLang;

Displays - 1.
Ie . bug only with 0, with other numbers there is no bug. I found something like this in the dock, but did not understand.
Please clarify :) Thanks in advance!

Answer the question

In order to leave comments, you need to log in

4 answer(s)
I
ivankomolin, 2018-02-27
@seredaes

Because you mixed up the place of the condition and the place of the value of the condition.
Why does it work with 0 like this:

//В switch пишется условие, результат выполнения которого ищется в case
switch(0) {
    case (0>2)://false, итог: 0==false, ответа да, case сработает
            $userLang = 1;
            break;
}

Why with 1 you won't notice:
//В switch пишется условие, результат выполнения которого ищется в case
switch(1) {
    case (1>2)://false, итог: 1==false, ответа нет, case не сработает
            $userLang = 1;
            break;
}

Why everything is fine with values ​​​​greater than 2x:
//В switch пишется условие, результат выполнения которого ищется в case
switch(3) {
    case (3>2)://true, итог: 3==true, ответа да, case сработает
            $userLang = 1;
            break;
}

Therefore, this is not a php bug. This is a bug that you wrote, inattentively reading the documentation.
What worked in some cases is just standard type manipulations for this language.

S
Stanislav B, 2018-02-27
@S_Borchev

what you wrote is the same

<?php

$userLang = 0;
switch(false) {
    case false:
            $userLang = 1;
            break;
}
echo $userLang;

userLang will be equal to 1. no bug

N
neol, 2018-02-27
@neol

You have a strange value in case. I don't think you really understand how switch works.
To compare with $userLang , the expression ($userLang>2) is implicitly cast to int, resulting in 0.
This is not a bug in PHP.

A
Alexey, 2018-02-27
@Azperin

php.net/manual/en/control-structures.switch.php
switch is an if with a comparison operator, you can't put a condition there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question