I'm using getopt to pass variables to my script, but I get the message:
PHP Notice: Undefined index:
Here's my code:
$MyOptions = getopt("c:hp:");
if ($MyOptions['c']) { //line wher error show up!
$MyClub = $MyOptions['c'];
} else {
$MyClub = '53';
}
What did I miss?
The problem is the index c
in your $MyOptions
array does not exist, you can avoid this in a number of ways, but my preferred option in this case would be to replace the entire if
-else
statement with;
$MyClub = $MyOptions['c'] ?? '53';
The ??
is the Null Coalescing operator.
The null coalescing operator (
??
) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction withisset()
. It returns its first operand if it exists and is notNULL
; otherwise it returns its second operand.
Please be aware this is only available from PHP 7, otherwise you will have to use an isset()
to check if the index exists.