Link to home
Create AccountLog in
Avatar of mmcw
mmcw

asked on

For loop question

I am tying this code:
It will not work
How to make this work?

Code:
for ($i=1; $i<=5; $i++) {
      ${'GoogleMapsAPI'.$i} = $i;
}

Result:
$GoogleMapsAPI1 = 1;
$GoogleMapsAPI2 = 2;
$GoogleMapsAPI3 = 3;
$GoogleMapsAPI4 = 4;
$GoogleMapsAPI5 = 5;
for ($i=1; $i<=5; $i++) {
	${'GoogleMapsAPI'.$i} = $i;
}

Open in new window

Avatar of Roger Baklund
Roger Baklund
Flag of Norway image

What do you want the code to do? In what way does it not work?
Avatar of Ionut A. Tudor
here how you achieve that
 

<?php
 
for ($i=0; $i<=5; $k="GoogleMapsAPI$i",$i++) {
	@$$k = $i;
}
 
echo $GoogleMapsAPI0;
echo $GoogleMapsAPI1;
echo $GoogleMapsAPI2;
echo $GoogleMapsAPI3;
echo $GoogleMapsAPI4;
 
?>

Open in new window

Avatar of mmcw
mmcw

ASKER

I  think the code:

for ($i=1; $i<=5; $i++) {
      ${'GoogleMapsAPI'.$i} = $i;
}

will not result in:
$GoogleMapsAPI1 = 1;
$GoogleMapsAPI2 = 2;
$GoogleMapsAPI3 = 3;
$GoogleMapsAPI4 = 4;
$GoogleMapsAPI5 = 5;

Or does it and is the problem somewhere else in my code?
and in my above code it will also work echo $GoogleMapsAPI5; because $i <= 5
If this wasn't what you were looking for let us know.

There is nothing wrong with your code! When I use it, and then print $GoogleMapsAPI1, I nicely get a 1.
<?php
 
for ($i=1; $i<=5; $i++) {
      ${'GoogleMapsAPI'.$i} = $i;
      
}
 
echo $GoogleMapsAPI1;
?>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of mmcw
mmcw

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Good to see it's working now!