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?

1
  • 1
    why are you not using arrays Commented Nov 26, 2015 at 5:24

2 Answers 2

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'];
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks a lot. It's working.
Glad that I helped you
@ 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?
Enclose in brackets => ($i+1) like this id=${'a' . ($i+1)}")
@ MyWay, thanks for helping me. Sorry, I tried in that way. But it's not working.
2
for($i=0; $i<5; $i++)
{
     $name = 'a' . $i;
     $$name = $arr [$i]['id'];
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.