How to fix undefined variable problem in php?

67 Views Asked by At

I have a php code in which I am getting the error message Notice: Undefined variable: c at LineA

<?php echo HelloWorld($a, $b = 6, $c); ?>  // LineA

The function definition is shown below:

function HelloWorld($a,$b = 0,$c = [],$max_text_length = 50) {


}

In order to fix the problem, I have added LineB above LineA.

<?php $c=[] ?> // LineB
<?php echo HelloWorld($a, $b = 6, $c); ?>  // LineA

Problem Statement:

I am wondering if there any way I can fix the undefined variable problem for that paritcular case.

2

There are 2 best solutions below

0
Simone Rossaini On

If you don't need to change the $c variable don't do it you have already set a default value in the function.

HelloWorld(1, 6); 
function HelloWorld($a, $b = 0,$c = [],$max_text_length = 50) {
    print_r([$a, $b,$c,$max_text_length]); 
}

Result:

Array
(
    [0] => 1  //<-- $a
    [1] => 6  //<-- $b
    [2] => Array //<-- $c
        (
        )

    [3] => 50 //<-- $max_text_length
)
3
Markus On

If you are able to modify the function call, you can try this:

<?php echo HelloWorld($a, $b = 6, $c ?? []); ?>

So that if $c is not already defined of if it is null, an empty array ([]) will be used. If $c is set, it will be used. See: https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op