1

I'm quite confused in how would I be able to create variable based on an array's values, my code is:

$a = array("red","black","white","green","blue");

for($i=0;$i>5;$i++)
{
$$a[$i] = '0.00';
}

echo $red;

I was under the impression that emulating a statement that says $red = '0.00'; would run properly but alas, it says undefined variable red.

2 Answers 2

2

use this:

for($i=0;$i<5;$i++)

you got error in loop, you have used '>' sign, so loop doesn't work, actually... :)

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

1 Comment

Oh omg, how did I not see that. That's why the $red isn't getting declared, that explains it. Thank you!
2

It's only your assignation that is wrong.

Use a foreach loop to make it easier, and it will work :

$a = array("red","black","white","green","blue");

foreach ($a as $val) {
    $$val = '0.00';
}

echo $red;

Output :

0.00

1 Comment

This is also a great answer! this looks more simpler than my for. This just didn't solve my problem, it also taught me a simpler method. I would up this answer although I don't have enough reps, sadly. I'd make sure to up this once I get 15 though.

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.