corning
corning

Reputation: 25

How do I use a variable in a new variable name?

I'm working with a while loop and I need to be able to assign the value of a variable to the name of a new variable. Here is the loop ($slide_number always returns a number):

$slide_number = theme_get_setting('slides_number');
$count = '1';

while ($count <= $slide_number) {
  $slide_path = theme_get_setting('slide_path_'.$count.'');
    if (file_uri_scheme($slide_path) == 'public') {
      $slide_path = file_uri_target($slide_path);
    }  
  $count++;  
}

So let's say $slide_number is 2. I need to produce $slide_path_1 and $slide_path_2, so how do I add the $count variable to $slide_path to create $slide_path_1 and $slide_path_2?

Upvotes: 0

Views: 68

Answers (5)

usumoio
usumoio

Reputation: 3568

What you are trying to do is really bad practice... Use an array to do this instead. Look into how arrays work, you can append all of your values together in a list with one and then you can view them however you need. Consider the following:

$slide_number = theme_get_setting('slides_number');
$count = '1';
$array_of_slides = array();

while ($count <= $slide_number) {
   $slide_path = theme_get_setting('slide_path_'.$count.'');
   if (file_uri_scheme($slide_path) == 'public') {

     $slide_path = file_uri_target($slide_path);

     // this line appends your value to the end of the array
     $array_of_slides[] = file_uri_target($slide_path);
   }  
   $count++;  
}

// this will print out the array so that you can see it
var_dump($array_of_slides);

Side note: the reason what you are trying to do is such bad practice is because if you had 4 billion variables declared as such your program will crash for sure and it might take your OS down with it.

Upvotes: 0

geekman
geekman

Reputation: 2244

$count=1;
$var1='$slide_path_'.$count;
$$var1="here you go";

this will create a variable by name $slide_path_1 and assign "here you go" to it

http://php.net/manual/en/language.variables.variable.php

Upvotes: 0

user1701047
user1701047

Reputation: 747

I'm confused. If you just need information from the previous run of the loop, have a variable at the end of the loop that holds that information. Or load all of this into a declared array and then do what you want with it after you load it.

Upvotes: 0

moonwave99
moonwave99

Reputation: 22817

Refer with:

${'slide_path' . $count}

Upvotes: 2

Sean Bright
Sean Bright

Reputation: 120644

While I don't recommand variable variables, this should do it:

$slide_path = "slide_path_" . $slide_count;
echo $$slide_path;

Upvotes: 2

Related Questions