Reputation: 3
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.
Upvotes: 0
Views: 44
Reputation: 54841
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
}
}
Upvotes: 1