1

I got this error message

Undefined variable: x in ../../../../.php on line 35

I get the error on this line.

$x .= $y->getContent();

This line of code is in a foreach loop.

How do I get rid of the error message.

If I replace the .= with just = I'm not getting the correct output.

I hope I provided enough information

And what does .= do? Thanks in advance.

Robert Verkerk
  • 694
  • 3
  • 10
  • 22

5 Answers5

3

.= is used (in your code) to concatenate the value of $x with result of ->getContent() call on $y and write the result back into $x.

Is like write $x = $x.$y

Of course if $x does not exists (like in your example I suppose; with "not exists" I mean that hasn't a value), regardless how you wrote your expression, this will fail. Moreover, $x and $y will be considerated strings so, please pay attention to your variables type (you can't concatenate two object, for example)

DonCallisto
  • 29,419
  • 9
  • 72
  • 100
1

$x.=$y is a shortcut for $x=$x.$y

so if $x = 'cat' and $y = 'fish' then the result of $x.=$y is 'catfish'

As to your error, you need to create the variable $x 1st, out side the loop:

$x='';
foreach($var as $y){
    $x.=$y;
}
Steve
  • 20,703
  • 5
  • 41
  • 67
1
$x = '';
foreach()
{
   $x .= $y->getContent();
}

*it is must to define $x becouse you are append value in $x *

wild
  • 340
  • 1
  • 3
  • 14
0

Define x before your loop : $x = '';

Sadok SFAR
  • 309
  • 2
  • 6
0

The .= operator is a string operator to concatenate strings.

$x .= $yis the same as $x = $x.$y

You could read about string operator s in the official PHP reference

If $x don't exist you can't concatenate it with $y, this is the reason of the error message.

Donnie Rock
  • 552
  • 1
  • 14
  • 27