Error with undefined PHP Variable in a site where it is undefined

1

guys I own a PHP project where I have a file with the functions that must be executed, in this same file I have declaration of the global variables one of these variables is:
$usua = $_SESSION['user']['username'];
This variable I use a lot in other functions where users have already logged in the system, but I do not use it in the functions for the recovery of access codes, the error that I get is that of undefined variable, I would like to know if can guide indicating how I can give instructions to my code so that when it is not defined the variable is omitted, or it is assigned the value 0 or null. try with a if (!$usua) but then in the function where I require the value of this variable with the call of global $usua does not work indicating that the variable is null, other times it says it is undefined etc etc.

    
asked by Jose M Herrera V 30.11.2018 в 02:45
source

1 answer

1

You can use isset to determine if the variable exists. For example:

// Si la variable existe se retorna TRUE y el texto se imprimirá.
if (isset($_SESSION['user']['username'])) {
    echo "Esta variable está definida, así que se imprimirá";
}

Now we can take this to the allocation of the value depending on its existence. One option could be the following:

$usua = isset($_SESSION['user']['username']) ? isset($_SESSION['user']['username']) : 0;

In the previous code what we are doing is to verify if it exists, in the case of returning "true" it assigns the value it contains. Otherwise, the value 0 (zero) is assigned.

I hope you find it useful. Greetings!

    
answered by 30.11.2018 / 03:07
source