Jump to content

Dynamically Generate Variables in a Loop


tereglow

Recommended Posts

Hello all,

 

I am trying to dynamically create variables in a loop.  For example:

 

myArray = array('Blue', 'Green', 'Yellow') {
for ($i = 0; $i < count($myArray); $i++) {
    $var.$i = "The color is $myArray[$i]";
}

 

What I'm looking to do is get "var1, var2, and var3" that I can then access outside of the loop.  These vars would be equal to the full, "My color is..." string.  The above generates an infinite loop of zeros for some reason.  Is there any way to do this in PHP?  I think I've done something similar in shell and possibly Perl.

 

Thank you for the help,

Tom

Link to comment
https://forums.phpfreaks.com/topic/52058-dynamically-generate-variables-in-a-loop/
Share on other sites

You could also do:

 

myArray = array('Blue', 'Green', 'Yellow') {
for ($i = 0; $i < count($myArray); $i++) {
    ${"var" . $i} = "The color is $myArray[$i]";
}
echo $var1;

 

or

 

$var = "var_name";
myArray = array('Blue', 'Green', 'Yellow') {
for ($i = 0; $i < count($myArray); $i++) {
    ${$var . $i} = "The color is $myArray[$i]";
}
echo $var_name1;

<?php
myArray = array('Blue', 'Green', 'Yellow') {
for ($i = 0; $i < count($myArray); $i++) {
    $newVar = 'var'. $i;
    $$newVar = "The color is $myArray[$i]";
}

echo $var1;
?>

 

There is no output from this!

 

Wouldn't expect there to be with a syntax error.

 

<?php
$myArray = array('Blue', 'Green', 'Yellow'); // removed { added $ before myArray.
for ($i = 0; $i < count($myArray); $i++) {
    $newVar = 'var'. $i;
    $$newVar = "The color is $myArray[$i]";
}

echo $var1;
?>

As effigy alluded to, this makes no sense. Why do you need to create distinct variables in the format $var1, $var2, etc. Why not just rereference the values in the format $arrayName[0], $arrayName[1], etc.

 

If you only wanted to create a variable for one or a couple values it might make sense, but not for all of them. Use the array.

<?php
myArray = array('Blue', 'Green', 'Yellow') {
for ($i = 0; $i < count($myArray); $i++) {
    $newVar = 'var'. $i;
    $$newVar = "The color is $myArray[$i]";
}

echo $var1;
?>

 

There is no output from this!

 

Wouldn't expect there to be with a syntax error.

 

<?php
$myArray = array('Blue', 'Green', 'Yellow'); // removed { added $ before myArray.
for ($i = 0; $i < count($myArray); $i++) {
    $newVar = 'var'. $i;
    $$newVar = "The color is $myArray[$i]";
}

echo $var1;
?>

 

I caught the curly brace error but I over looked $ symbol. lol

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.