简体   繁体   中英

PHP Variable Variable for loop

hey guys is this even possible to be done in php

<?php   
$sectorcount = $row_SectorCount['COUNT(*)'];
//number of rows in database
for ($i = 1; $i <= $sectorcount; $i++)
{
${spendingname . $i}= array();
${spendingpercent . $i} = array();
${spendingid . $i} = array();

mysql_select_db($database_conn2, $conn2);
$query_Spending = "SELECT CONCAT(spending.SectorID, spending.ExpenditureID) AS 'SpendingID',
expenditure.ExpenditureName, spending.SpendingPercent, spending.SectorID
FROM spending   
INNER JOIN expenditure ON spending.ExpenditureID = expenditure.ExpenditureID
WHERE spending.SectorID = ".$i;
$Spending = mysql_query($query_Spending, $conn2) or die(mysql_error());
$totalRows_Spending = mysql_num_rows($Spending);
while($row_Spending = mysql_fetch_assoc($Spending))
{
${spendingname.$i}[] = $row_Spending['ExpenditureName'];
${spendingpercent.$i}[] = $row_Spending['SpendingPercent'];
${spendingid.$i}[]= $row_Spending['SpendingID'];
}
mysql_free_result($Spending);
}

i was planning to use this here in this context. having an array to draw out the values using a where clause and display them individually

This is what you are looking for:

for ($i = 0; $i < 14; $i++) {
    ${'name' . $i} = $i;
}

echo $name3;

But you should just use an array:

$name = array();
for ($i = 0; $i < 14; $i++) {
    $name[$i] = $i;
}

echo $name[3];

If you need an array in an array, go ahead and do that too. If you need more nested arrays than that, you should probably be using a class somehow instead of all that array nesting.

First off, I second the suggestion to use an array instead. Variable variables are not meant to be used like this.

That said, it is possible by accessing ${$name.$i} , or perhaps doing something like

$varname = $name.$i;
$$varname = 1; // or read from $$varname

Use an array. That's what they're there for.

As Kolink said, that is what an array is for!

However, What you are asking can be achieved:

Read More Here

Basically,

<?php

for($i=0; $i<=13; $i++){

    $varname = "name" . $i;
    $$varname=$i;

}

echo $name1; // 1

?>

It will not give desired output 1 instead will give 13

What s the reason of doing like this. you can make array a access is later on use

 for($i=0; $i<=13; $i++)
 {
        $name[$i]=$i;
 }

      echo $name[1];                    *//it will echo 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM