0

I have the following results page from the previous form:

<?php
//Get the form results (which has been converted to an associative array) from the $_POST super global
$musicgenres = $_POST['music'];

//Sort the values by rank and keep the key associations.
asort($musicgenres, SORT_NUMERIC );

//Loop over the array in rank order to print out the values.
foreach($musicgenres as $music => $rank)
{
    echo "$music is your $rank choice";
   echo "<br>";
 }
?>

Here is an example of the output (without the bullets):

  • Rap is your 1 choice
  • Rock is your 2 choice
  • Jazz is your 3 choice
  • etc....

I'm thinking that putting this into a table will not be easy or clean. How can assign these values to incremental variables?

e.g.

  • $musicrank1 = rap
  • $musicrank2 = rock
  • $musicrank3 = jazz
  • etc....
2
  • What exactly are you trying to achieve here? Dynamically creating an undetermined number of variables looks like a hack. Commented Aug 11, 2015 at 9:44
  • make a music_ranks table and insert rank and music .Then do whatever you want to do. If it is dynamic then update the music_rank table using query. Commented Aug 11, 2015 at 9:47

3 Answers 3

3

Try this

$i = 0;
//Loop over the array in rank order to print out the values.
foreach($musicgenres as $music => $rank)
{
    ${ "musicrank". ($i) }  =   $music;
    echo "$music is your $rank choice";
   echo "<br>";
   $i++;
 }

after foreach you'll have your variables.

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

Comments

2

Using a table is much easier than creating arbitrary variables. With the table you just have to say $musicrank[1] instead of $musicrank1 and you can iterate over the table if you want to.

As a rule of thumb, if you'd assign each value in the table manually, you should use variables instead. But you are using a loop, so it's a pretty obvious case for tables.

Comments

0

use this script : for add array with comma

        `$no = 0;
        foreach($sql2 as $row2)
        {
            $row["store_name"] .= ($no != 0) ? ", " : "";
            $row["store_name"] .= $row2["store_name"];

            $no++;
        }

Comments

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.