Jump to content

Naming variable with a variable & setting variable with a variable


Showcase

Recommended Posts

I just started to learn php. Don't know if this one is possible, or if I'm approaching this the right way. I'm just learning by attempting to create something that reads an XML file, adds to it, then displays the final result. The XML file holds a playlist for a flash music player I made. This probably won't get used much, just thought I'd start learning php by designing this.

 

I'm starting off with making the basic functionalities of the php. What I'm simply trying to do is set variables to inputted information using an html form. Now I know how to do that using "$_POST['song0name']" and 'song1URL' but the amount of songs being added is going to be "adjustable" I guess you can call it. So therefore, I'd like to use the do, while expression. The code I'm looking at looks something like this:

 

$myVar = 0;

do

{

    $songname =

    echo ($songname);

    $myVar++;

} while ($myVar < $songAmount);

 

What I'm currently trying to do at the moment is to simply assign the value of $_POST['songname0'] to $songname, but using the number from $myVar for the "id" I guess it's called. Something like "$_POST['songname' . $myVar] but I can't seem to figure out how to make this work. I'm running into some problems as the code treating the value as a string rather than grabbing the value of the $_POST variable.

 

I might just being going about this completely wrong, I'm not sure. Maybe someone here can give me some input, show me how to do it, or point me in the right direction. Thanks for any help.

Great to see a well formulated question (for once) ;)

 

If you have a form with multiple input fields ranging from songname0 to songname9 in names, you could put the names in an array, using while as you wanted, or even better (for this example), for:

 

<?php
$songAmount = 10;
// define the empty array to hold the song names
$songArray = array();
// $i = 0; keep on looping as long as $i < $songAmount; increase $i by 1 at the end of each iteration
for ($i = 0; $i < $songAmount; $i++) {
$songArray[] = $_POST['songname'.$i];
}
// $songArray now contains array('first songname', 'second songname', ...)
?>

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.