0

I've been trying to find a quicker way to add the following code ...

    if (empty($insert1 = insert($language_id, 'step_one', 1))) {
        $insert1 = insert(1, 'step_one', 1);
    }

    if (empty($insert2 = insert($language_id, 'step_one', 2))) {
        $insert2 = insert(1, 'step_one', 2);
    }

    if (empty($insert3 = insert($language_id, 'step_one', 3))) {
        $insert3 = insert(1, 'step_one', 3);
    }

// continues up to $insert35

I can build an array of values showing ...

$array = array('$insert1', '$insert2', '$insert3'); // up to $insert35

But when I loop through the array, it doesn't work ...

$count = 1;
foreach($array as $value) {

    if (empty($value = insert($language_id, 'step_one', $count))) {
        $value = insert(1, 'step_one', $count);
    }
$count++;
}

In the body of the page, I am calling the snippets as ...

echo $insert1;

echo $insert2;

echo $insert3;

But the error shows as ...

Undefined variable: insert1

Undefined variable: insert2

Undefined variable: insert3

etc

Currently I am writing each step manually but there must be a better way to do it using a loop.

4
  • 1
    What on earth is insert()??? Commented Jan 6, 2017 at 18:40
  • This is what arrays for. Commented Jan 6, 2017 at 18:44
  • Are you running this insert generation code in a function? Commented Jan 6, 2017 at 18:44
  • Looks like a for ($x=1; $x<$max; $x++) {} would do it quite nicely Commented Jan 6, 2017 at 18:48

1 Answer 1

1

A sample with arrays:

$count = 35;
$insert_results = [];
for ($i = 0; $i < $count ; $i++) {
    $res = insert($language_id, 'step_one', $i + 1);
    if ($res) {
        // if `insert` runs successfully
        $insert_results[$i] = insert(1, 'step_one', $i + 1);
    } else {
        // if `insert` fails, you can even 
        // omit `else`-part if you want
        $insert_results[$i] = false;    // or NULL or -1
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.