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 = "";
3
  • 1
    why you used single quotes? you can use double quotes or leave it without quotes Commented Dec 23, 2017 at 13:11
  • @AnimeshSahu If I remove the quotes, it then says that all the variables are undefined. Commented Dec 23, 2017 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. Commented Dec 23, 2017 at 13:43

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Oh brilliant, thanks for including the link to that answer as I think that's much simpler than using an array. Thanks again!
0

Easier way:

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

2 Comments

Is it more beneficial to use this than $hi = $bye = $hello = "";?
In case of List, variables go NULL when used string, actually $hi = $bye = $hello = ""; is better.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.