Reputation: 3
So, I have the following PHP code.
for($i = 1; $i <= 3; $i++) {
${'product' . $i . 'Id'} = ${'_GET["product' . $i . 'Id"]'};
}
I want the output to be something similar to this.
$product1Id = $_GET["product1Id"];
$product2Id = $_GET["product2Id"];
$product3Id = $_GET["product3Id"];
So that I can echo them later.
echo $product1Id;
echo $product2Id;
echo $product3Id;
Upvotes: 0
Views: 353
Reputation: 23958
Use extract to make the array $_GET individual variables.
extract($_GET);
Echo $product1Id . $product2Id . $product3Id;
Since I can't make this "happen" on a online PHP tester I created an array just like your GET array.
See the demo here.
https://3v4l.org/RqjRd
Upvotes: 0
Reputation: 86
I hope this helps you <3. For getting out puts like this($product1Id = $_GET["product1Id"]) using for , you can make a for like this ! you can make an array that each elements of that array contains one of the get values you get !I think This is better than making lots of variables ! Try to put your values in an array like the code below ! The first step is to make an array with 0 elements.
$array_get_values = new array();
now its time to make the for , and put values in it.
for($i=1 ; $i =< 3;$i++)
{
$array_get_values[] = $_GET["product".$i."Id"];
}
and now you have all your values in array and you can call them by their address.
Note : $array_get_values[] => this piece of code , adds new element to our array
i hope i've helped you ! Good luck bro
Upvotes: 0
Reputation: 16963
You're almost there, your for
loop should be like this:
for($i = 1; $i <= 3; $i++) {
${'product' . $i . 'Id'} = $_GET['product' . $i . 'Id'];
}
Or, instead of this for
loop you can simply do extract($_GET);
. This will directly give you the required variables and the associated values. Reference: http://php.net/manual/en/function.extract.php
Upvotes: 1
Reputation: 109
try this.
for($i = 1; $i < 3; $i++) {
${'product' . $i . 'Id'} = $_GET["product{$i}Id"];
}
Upvotes: 1