先日countをforの中に書くなよって話を書いたらid:fbisさんよりコメントいただきまして
for($i=0; $c=count($array); $i<$c; $i++){ ... }
と書いているとのこと。
coool!
ナイスギーク!略してNG(ヤメ
アレよね、入門書もたいてい、forの最初の部分が「初期条件」とは書いてるけど、ここに複数書く例ってあまり載せないものね。というわけで、変数の個数を「ローカル(forの中だけで)で使うなら」この方法がいいと思う。
もいっこ。同じくid:fbisさんに頂いたのですが、array_pushの方が速いケースもあるらしい。
これは基本的には
Manualより、
注意: もし配列にひとつの要素を加えるために array_push() を使用するなら、 関数を呼ぶオーバーヘッドがないので、$array[] = を使用するほうがいいです。
ってことでいいんじゃないかねえ。
id:kmachuさんの言っていたように、配列の個数を計算してからやってるみたいです。
/* {{{ proto int array_push(array stack, mixed var [, mixed ...]) Pushes elements onto the end of the array */ PHP_FUNCTION(array_push) { zval ***args, /* Function arguments array */ *stack, /* Input array */ *new_var; /* Variable to be pushed */ int i, /* Loop counter */ argc; /* Number of function arguments */ /* Get the argument count and check it */ argc = ZEND_NUM_ARGS(); if (argc < 2) { WRONG_PARAM_COUNT; } /* Allocate arguments array and get the arguments, checking for errors. */ args = (zval ***)safe_emalloc(argc, sizeof(zval **), 0); if (zend_get_parameters_array_ex(argc, args) == FAILURE) { efree(args); WRONG_PARAM_COUNT; } /* Get first argument and check that it's an array */ stack = *args[0]; if (Z_TYPE_P(stack) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "First argument should be an array"); efree(args); RETURN_FALSE; } /* For each subsequent argument, make it a reference, increase refcount, and add it to the end of the array */ for (i=1; i<argc; i++) { new_var = *args[i]; new_var->refcount++; if (zend_hash_next_index_insert(Z_ARRVAL_P(stack), &new_var, sizeof(zval *), NULL) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot add element to the array as the next element is already occupied"); efree(args); RETURN_FALSE; } } /* Clean up and return the number of values in the stack */ efree(args); RETVAL_LONG(zend_hash_num_elements(Z_ARRVAL_P(stack))); } /* }}} */