-1

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.

flash
  • 1,455
  • 11
  • 61
  • 132
  • 2
    `I am wondering if there any way I can fix the undefined variable problem for that paritcular case.` Yeah. Define `$c`. – tkausl Jul 19 '22 at 06:34
  • Remove $c if you do not intend to define it. `` – subodhkalika Jul 19 '22 at 06:50
  • you can use an if-else block to see is variable `$c` is set or not for calling the `HelloWorld` function with or without variable `$c` like `if (isset($c))` then call `HelloWorld($a, $b = 6, $c)` else `HelloWorld($a, $b = 6)` – Al-Amin Jul 19 '22 at 07:06

2 Answers2

0

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
)
Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34
-1

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

Markus
  • 81
  • 4