0

I have an array that has the same structure as this:

$DB = array(
   "1" => array(
       "name" => "Bob",
       "othernames" => "Bill"
   ),
   "2" => array(
       "name" => "Gill",
       "othernames" => "Gillian"
   )
);

I then have a foreach loop that iterates over the array similar to this:

foreach(array_keys($array) as $id) {
    echo $id; // would echo "1" or "2", etc.
    // do some other time-consuming operations with $id and the array
}

Some of these time-consuming operations will take longer than others. They will all return a variable with a boolean value.

Currently, I am processing each key one after another, which is causing very long load times.

How can I "iterate" (I'm not sure this is still classed as iteration) over each key in the array simultaneously, so that the page load time will not be affected so severely by the number of items in the array?

  • It sounds like what you're looking for is threading: [link](http://php.net/manual/en/book.pthreads.php) – Zackary Murphy Dec 30 '16 at 14:30
  • @ZackaryMurphy Would this use one thread per "iteration"? The operations being performed are `ping` via `exec()`. I should have mentioned this, I'll add this in. Assigning `ping`s to cores so directly is less than ideal, but I'll look through the link you gave, thanks! –  Dec 30 '16 at 14:41
  • So, this question is basically not about iterating arrays per se, but how to perform multi-threaded operations in PHP? If so, consider reading [How can one use multi threading in PHP applications](http://stackoverflow.com/questions/70855) and maybe search for other relevant topics already discussed. – Anton Samsonov Dec 30 '16 at 15:43
  • Possible duplicate of [How can one use multi threading in PHP applications](http://stackoverflow.com/questions/70855/how-can-one-use-multi-threading-in-php-applications) – Anton Samsonov Dec 30 '16 at 17:24
  • @AntonSamsonov No, I'm not looking to directly assign cores to iterations. I'm looking for a way to directly correlate a foreach loop with multiple cores. –  Dec 30 '16 at 17:41
  • Multi-threaded computing is not about assigning cores, — it is about creating separate threads or processes and wait for them to finish asynchronously. The job of distributing threads among processor cores is usually done by operating system, there is no need to pin threads to cores manually. As for “directly correlating `foreach` loop with multiple cores”, PHP does not have a language construct for parallel processing. – Anton Samsonov Dec 30 '16 at 17:46

0 Answers0