3

My PHP code has several PHP variables like this.

$a0 = $arr[0]['id'];
$a1 = $arr[1]['id'];
$a2 = $arr[2]['id'];
$a3 = $arr[3]['id'];
$a4 = $arr[4]['id'];

I want to create these PHP variables using a for loop This is what I tried so far. But it’s not working.

for($i=0; $i<5; $i++)
{
  $a.''.$i = $arr [$i]['id'];
}

Can anyone please help me?

A J
  • 3,970
  • 14
  • 38
  • 53
Aishy
  • 45
  • 8

2 Answers2

2
for($i=0; $i<5; $i++)
{
     $name = 'a' . $i;
     $$name = $arr [$i]['id'];
}
Nick
  • 9,735
  • 7
  • 59
  • 89
2

Simply enclose in brackets {}

for($i=0; $i<5; $i++)
{
    ${'a'.$i} = $arr[$i]['id'];
}

Now

echo $a0; //$arr[0]['id'];
echo $a1; //$arr[1]['id'];
echo $a2; //$arr[2]['id'];
echo $a3; //$arr[3]['id'];
echo $a4; //$arr[4]['id'];
Thamilhan
  • 13,040
  • 5
  • 37
  • 59
  • Thanks a lot. It's working. – Aishy Nov 26 '15 at 05:51
  • Glad that I helped you – Thamilhan Nov 26 '15 at 06:10
  • @ MyWay, Thanks again. It works perfectly. Arose another problem regarding this. I have several queries like this. $query1=mysql_query("update places set newdistance='$d0' where id=$a1"); $query2=mysql_query("update places set newdistance='$d1' where id=$a2"); I made another for loop to create these queries. It's like this.for($i=0; $i<3; $i++){ ${"query" . $i}=mysql_query("update places set newdistance=${'d' . $i} where id=${'a' . $i+1}"); } The problem is in where clause, $i+1 is not working. Can you guide me how to do it? – Aishy Nov 26 '15 at 06:13
  • Enclose in brackets => ($i+1) like this `id=${'a' . ($i+1)}")` – Thamilhan Nov 26 '15 at 06:26
  • @ MyWay, thanks for helping me. Sorry, I tried in that way. But it's not working. – Aishy Nov 26 '15 at 06:29