Search code examples
phparraysvariablescycle

Create arrays with cycles


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.


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.