Skip to content
Advertisement

array_push does not add value in case of used inside of foreach > if

I’m currently working on a website for my project, but for some reason when everything is as it has to be ( session is started, session variable is defined ), then only array_push() function doesn’t add the value to session variable, when I move array_push() out of if, foreach and if (if contains foreach and foreach contains another if), it works fine, I already tried to put it to first if, then to foreach but it didn’t help. So it works only when it is out of that code (When it is not in that if, which contains foreach, which contains another if). Please try to understand, my English is not well.

What do I have to do to fix it?

if(isset($_GET["setLang"])) {
    foreach ($languages as $item) {
        if($item === $_GET["setLang"]) {
            $_SESSION["selLang"] = $item;
            array_push($_SESSION["sessionMessage"], "Language changed successfully!");
            header("location: index.php?path=/");
            exit();
        }
    }
}

Advertisement

Answer

Since the code work correctly out of the if statement , it’s cleary evident that the condition cause the problem

$item === $_GET["setLang"]

Using triple = will check value and type . So may be the type of each ones is different than other .

Replace it with :

$item == $_GET["setLang"] // only use two =
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement