Search code examples
phparraysfunctionglobal-variableslocal-variables

How can I use a value from a global array locally in a function in PHP?


Thanks if you are reading this. My problem is that I can't access inside my array from a function. For example:

$users = ["admin" => "admin","Alejandro" => "8345245"];
$userName = "Alejandro"
$UserPass = "8345245";
function checkUser(){
if( $users[$userName] == $userPass){
    return "The password is good";
}

This is my problem, I know to use global variables in a function I can use GLOBALS but here in an array if I use $GLOBALS["users[$GLOBALS["userName"]"] it does not work well. Thank you so much.


Solution

  • See; The global keyword. You can simply use global $users; at the beginning of your function. Like this:

    $users = ["admin" => "admin","Alejandro" => "8345245"];
    $userName = "Alejandro"
    $UserPass = "8345245";
    
    function checkUser() 
    {
        global $users,$userName,$UserPass;
        if( $users[$userName] == $userPass) {
            return "The password is good";
        }
    }
    
    echo checkUser();
    

    But this would make more sense:

    $users = ["admin" => "admin","Alejandro" => "8345245"];
    
    function checkUser($userName,$UserPass) 
    {
        global $users;
        if( $users[$userName] == $userPass) {
            return "The password is good";
        }
    }
    
    echo checkUser("Alejandro","8345245");