0

I'm trying to define three empty variables through a foreach loop to make my code cleaner. This is what I've tried, however I see the error:

Notice: Undefined variable: hi

foreach(['$hi','$bye','$hello'] as $key) {
    $key = "";
}

$hi .= "hello";

When I remove the foreach loop and simply define each empty variable one by one, like this, it works:

$hi = "";
$bye = "";
$hello = "";
The Codesee
  • 3,714
  • 5
  • 38
  • 78
  • 1
    why you used single quotes? you can use double quotes or leave it without quotes –  Dec 23 '17 at 13:11
  • @AnimeshSahu If I remove the quotes, it then says that all the variables are undefined. – The Codesee Dec 23 '17 at 13:13
  • 1
    PHP101 - Whenever you put something in quotes, it becomes a string. '$hi','$bye','$hello' are all strings so you can not pass them as variables to concat values to them. – omukiguy Dec 23 '17 at 13:43

4 Answers4

1

You're assigning to $key, not to the variable that's named by it. To indirect through a variable, you need to use $$key. But the value of the variable shouldn't include the $, just the variable name.

foreach (['hi', 'bye', 'hello'] as $key) {
    $$key = "";
}
$hi .= "hello";

However, if you ever find yourself using variable variables like this, you're almost certainly doing something wrong. You should probably be using an associative array instead.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You have strings which are saved in $key. So the value of $key is a string and you set it to "".

Later you want to append something to a variable you never used.

Try to remove the ' and write

foreach([$hi, $bye, $hello] as $key) {

Generally thats not the best way to initialise multiple variables. Try this

Initializing Multiple PHP Variables Simultaneously

  • Oh brilliant, thanks for including the link to that answer as I think that's much simpler than using an array. Thanks again! – The Codesee Dec 23 '17 at 13:18
0

Easier way:

list($hi, $bye, $hello) = "";

Don Valdivia
  • 201
  • 2
  • 4
0

foreach creates a new array variable in memory, so you only clear these values inside the array in memory which is useless out of the foreach sentence. the best way is:

$h1=$bye=$hello="";

I didn't think that a foreach process will work more fast than a Simple equal (=), foreach function uses more CPU resources than a simple =. That's because the math CPU exists.

Yahya Hussein
  • 8,767
  • 15
  • 58
  • 114