Question

I have the following code:

for ($i = 1; $i <= $j; $i++) 
{
    $goods_{$i} = array(
        $_POST["'goods'.$i'_title'"],
        $_POST["'goods'.$i.'_package'"],
        $_POST["'goods'.$i.'_nmr'"]
    );
}

I hoped that it could make this in first step of the cycle:

$i =1;
$goods_1 = array(
    $_POST['goods1_title'], 
    $_POST['goods1_package'], 
    $_POST['goods1_nmr']
);

and so on in other steps.

Was it helpful?

Solution

I follow AbraCadaver's sentiments:

Why in the world are you doing this? You are using arrays, keep using them.

As such, I would write the code simply using an Array:

$goods = array();
for ($i = 1; $i <= $j; $i++) 
{
    // Assign to an index in the already created array,
    // but DO NOT create a new variable.
    $goods[$i] = array(
        // Also make sure these are correct ..
        $_POST["goods{$i}_title"],
    );
}

If you really want to create dynamic variables - ick! - see variable variables.

OTHER TIPS

Should be

    $_POST["goods{$i}_title"],
    $_POST["goods{$i}_package"],
    $_POST["goods{$i}_nmr"]

It can be done like this:

for ($i = 1; $i <= $j; $i++) 
{
    ${"goods_$i"} = array(
        $_POST["'goods'.$i'_title'"],
        $_POST["'goods'.$i.'_package'"],
        $_POST["'goods'.$i.'_nmr'"]
    );
}

You can read more about this topic in related PHP documentation.

The result of "'goods'.$i'_title'" will be 'goods'.1'_title', in case that you want it to be goods1_title then use following code instead:

for ($i = 1; $i <= $j; $i++) 
{
    ${"goods_$i"} = array(
        $_POST["goods{$i}_title"],
        $_POST["goods{$i}_package"],
        $_POST["goods{$i}_nmr"]
    );
}

Another bug might be that in 1 case you use .$i. and in other 2 cases you use .$i without the last ..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top