3

I am trying to create a dynamic variable. I have a loop and I want it to loop through the records and create a variable for each record. My code:

$ct = 1;
foreach ($record as $rec){
  $var.$ct = $rec['Name'];
  $ct = $ct + 1;
}

echo $var1;

When I try to use the above code, it gives me an error saying the $var1 variable doesn't exist/undefined? Is it possible in PHP to create dynamic variables like the above example. If so, what am I doing wrong?

4
  • What is $var?? Commented Sep 24, 2019 at 15:16
  • My variable that im setting. The constant portion of the variable. It could be anything $name.$ct Commented Sep 24, 2019 at 15:17
  • 6
    Use arrays instead. Commented Sep 24, 2019 at 15:17
  • 2
    why are you not using array?? Commented Sep 24, 2019 at 15:18

5 Answers 5

3

You're looking for variable variables.

Create the variable name as a string, and then assign it:

$ct = 1;
foreach( $record as $rec )
{
  $name = 'var'.$ct;
  $$name = $rec['Name'];
  $ct++;
}

echo $var1;

It would be much better to create an array, though:

$names = [ ];

foreach( $record as $rec )
{
  $names[] = $rec['Name'];
}

echo $names[0];
Sign up to request clarification or add additional context in comments.

1 Comment

To be clear: It's not just that arrays are a much better solution to the problem, but also that using variable variables is virtually always the worst solution for anything.
2

You can use different syntax with {}

$ct = 1;

foreach ($record as $rec){
    ${'var' . $ct++} = $rec['Name'];
}

echo $var1;

Although isn't it better just to use an array?

Working fiddle

2 Comments

I am getting undefined variable still when using your syntax. Have you tested this?
yes I have ;) let me include a fiddle just to prove sandbox.onlinephpfunctions.com/code/…
0

You can with a double $.

    $var = "variable";
    $$var = "test";

    echo $variable;
    //echoes "test"

in your example:

$ct = 1;
foreach ($record as $rec){
$varname = "var" . $ct;
  $$varname = $rec['Name'];
  $ct = $ct + 1;
}

echo $var1;

Comments

0

Please try this, let me know if it works for you. I use a prefix with the dynamic variable.

$ct = 1;
$prefix = 'var';
foreach ($record as $key=>$rec){
  $temp = $ct;
  $ct = $prefix.$ct;
  $$ct = $rec;
  $ct = $temp + 1;
}

echo $var1;

Comments

0

You can do that using array easily. But if you really want it to be in dyanamic vairable individually, in that case also , I would like to suggest you to get help in array way. This way, you can track you variables.

In the below mentioned way, you event don't need to take a extra variable like $ct. Just an array $var and applying extract method on it after the loop will do the trick.

$var = [];

foreach( $record as $k => $rec )
{
 $var['var'.$k] = $rec['Name'];

}

extract($var);

echo $var0; //or $var_1 or $var_2

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.