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

PHP

Avatar of undefined
Last Comment
pepio

8/22/2022 - Mon
Roger Baklund

What do you want the code to do? In what way does it not work?
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

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?
Your help has saved me hundreds of hours of internet surfing.
fblack61
Ionut A. Tudor

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.

pepio

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
mmcw

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
pepio

Good to see it's working now!
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.