1

I am trying to run a function for every element in an array using array_walk and try and catch so i can tell if any elements haven't run through the function successfully.

Once all elements have run through the function i need to respond with a complete callback.

In my code below though the complete json_ecnode is being run everytime rather than at the very end. What am i doing wrong? Also is this the most efficient way to do this?

$products = array('shirt','skirt','jumper','lingerie','makeup','top','trousers','coats');

$i = 0;
function createProducts(&$item, $key){
    try {
        // try something
    }
    catch(Exception $e) {
        // error
    }
    $i++;
    if($i > count($products)) { json_encode('complete'); }
}

array_walk($products, 'createProducts');
odd_duck
  • 3,941
  • 7
  • 43
  • 85
  • If you'd activate error reporting, you'd see your problem: variable scope. Read http://stackoverflow.com/a/16959577/476. But what you're trying to do here seems extremely odd from front to back. – deceze Sep 18 '14 at 08:46

3 Answers3

1

Well you could do something like this:

$products = array('shirt','skirt','jumper','lingerie','makeup','top','trousers','coats');
$count = count($products);
$i = 0;
array_walk($products, function(&$item, $key) use (&$i, $count){ // using anonymous
    try {
        // try something
        echo "<strong>$item</strong><br/>";
    }
    catch(Exception $e) {
        // error
    }

    $i++;
    if($i == $count) {

        echo 'completed at ' . $i;
        // execute something
    }
});
Kevin
  • 41,694
  • 12
  • 53
  • 70
0

The $i will always be 1, because every time you execute the function you get a new instance of that variable.

smoove
  • 3,920
  • 3
  • 25
  • 31
0

Additionally to Ghost answer, here is a way to do it with an anonymous call, but you still define the function previously, and not right when you use it. (Which is better if you intent to re-use it later on)

$products = array('shirt','skirt','jumper','lingerie','makeup','top','trousers','coats');

$i = 0;
$callback = function (&$item, $key) use ($i) {
    try {
        // try something
    }
    catch(Exception $e) {
        // error
    }
    $i++;
    if($i > count($products)) { json_encode('complete'); }
};

array_walk($products, $callback);
Clément Malet
  • 5,062
  • 3
  • 29
  • 48