2

I have a foreach loop that calls a function from an array_push but I get an error:

$product_export_array is empty

$product_export_array = array();
$_ProductIds = array('0','1', '2', '3');

function addProduct ($product_data, $sku_for_product) {
    array_push($product_export_array, array('sku' => $sku_for_product,);
}

foreach ($_ProductIds as $key=>$_product) {
    $simple_sku = 'abc' . $product;
    addProduct($_product, $simple_sku);
}
0

1 Answer 1

4

Pass it as reference (function argument starts with &, '&$xxx'):

$product_export_array = array();
$_ProductIds = array('0','1', '2', '3');

foreach ($_ProductIds as $key=>$product) {
    $simple_sku = 'abc';
    addProduct($product, $simple_sku, $product_export_array);
}

function addProduct ($product_data, $sku_for_product, &$export) {
    array_push($export, array('sku' => $sku_for_product));
}
var_dump($product_export_array);

Then elements added in function will be visible in code where you call function.

Sign up to request clarification or add additional context in comments.

2 Comments

It's working too, and by your comment in the other response, it seems a better solution

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.