PHP: Run two foreach loops at the same time

@reference: http://stackoverflow.com/questions/2556998/how-do-you-combine-two-foreach-loops-into-one

SPL MultipleIterator
@reference: http://docs.php.net/class.multipleiterator

// ArrayIterator is just an example, could be any Iterator.
$a1 = new ArrayIterator(array(1, 2, 3, 4, 5, 6));
$a2 = new ArrayIterator(array(11, 12, 13, 14, 15, 16));

$it = new MultipleIterator;
$it->attachIterator($a1);
$it->attachIterator($a2);

foreach($it as $e) {
  echo $e[0], ' | ', $e[1], "\n";
}

Prints

1 | 11
2 | 12
3 | 13
4 | 14
5 | 15
6 | 16

Advertisements

ip2long vs INET_ATON

Source: http://mwillis.co.uk/mysql/ip2long-vs-inet_aton/

PHP ip2long() sometimes return negative integers,
while MySQL INET_ATON() function returns only positive numbers.

Ensure PHP ip2long() returns only positive intergers:

sprintf("%u", ip2long("254.254.254.254"));
$ip = ip2long($ip_address);
if ($ip < 0){ $ip += 4294967296; }

For-loop with two counting variables

Perma Link: http://stackoverflow.com/questions/1172553/php-for-loop-with-2-variables/1172565#1172565

for ($i=0, $k=10; $i<=10 ; $i++, $k--) {
    echo "Var " . $i . " is " . $k . "<br>";
}

Gumbo, Author of this code snippet:
The two variables $i and $k are initialized with 0 and 10 respectively. 
At the end of each each loop $i will be incremented by one ($i++) and $k decremented by one ($k—).
So $i will have the values 0, 1, …, 10 and $k the values 10, 9, …, 0.

PHP Multi-Threads / Multi-Processes

By the use of curl_multi_init() (PHP5) or stream_select() (PHP5) or  pcntl_fork (PHP4+), we can stimulate multi-thread/multi-process environment on PHP

External Links:

using stream_select: Develop multitasking applications with PHP V5

using curl_multi_init: PHP curl_multi example of parallel GET requests

using pcntl_fork (chinese): 多采多姿的程式筆記#1, #2

forum quote(chinese): EcStart PHP 技術討論論壇

PHP是與host環境相關的腳本語言,通常狀況下不會使用thread的,有的話也是host的問題,與php沒有關係。(你用的話,會有同步等等問題,甚至會有可能造成host運作不穩定)

但是如果把php當作shell script等等獨立的語言工具來用的話,是可以模擬的。

php本身應該沒有提供thread的函數,但是有multi-process的吧。

請用google找找。

我在酷學園有看過一些討論:
http://phorum.study-area.org/index.php/topic,44942.0.html
http://phorum.study-area.org/index.php/topic,47238.0.html(這篇有提到一點同步機制)

另外,參考一下這一篇:
http://www.ibm.com/developerworks/web/library/os-php-multitask/?ca=dgr-lnxw06PHP5multitasking
(用php5模擬多工)