Re: cvs: phpdoc /en/reference/filesystem/functions glob.xml

From: Date: Tue, 07 Sep 2004 18:36:49 +0000
Subject: Re: cvs: phpdoc /en/reference/filesystem/functions glob.xml
References: 1 2 3  Groups: php.doc 
Request: Send a blank email to phpdoc+get-969363871@lists.php.net to get a copy of this message
So, using count() in a for is bad, but okay in a foreach ?
foreach makes a copy, for and each work directly on the subject. the reason you were told to evaluate the count into a tmp var was to save the loop from re-evaluating a constant (in most cases, for the duration of the loop) value. The following snippet illustrates this: <?php // for: // with count: evaluated every iteration: $r = range(0,4); for ($i=0; $i<count($r); $i++) { echo "$i: {$r[$i]}\n"; if ($i == 4) $r[] = 'a'; } echo "-----\n"; // with tmp var evaluated once: $r = range(0,4); $c = count($r); for ($i=0; $i<$c; $i++) { echo "$i: {$r[$i]}\n"; if ($i == 4) $r[] = 'a'; } echo "-----\n"; echo "-----\n"; // foreach: // always makes a copy (no need for tmp var): $r = range(0,4); foreach ($r AS $i => $v) { echo "$i: $v ({$r[$i]})\n"; if ($i == 4) $r[] = 'a'; } echo "-----\n"; echo "-----\n"; // each: // each works directly on the subject: $r = range(0,4); while (list($i, $v) = each($r)) { echo "$i: $v ({$r[$i]})\n"; if ($i == 4) $r[] = 'a'; } ?> Output: sean@iconoclast:~/php/tmp$ php loops.php 0: 0 1: 1 2: 2 3: 3 4: 4 5: a ----- 0: 0 1: 1 2: 2 3: 3 4: 4 ----- ----- 0: 0 (0) 1: 1 (1) 2: 2 (2) 3: 3 (3) 4: 4 (4) ----- ----- 0: 0 (0) 1: 1 (1) 2: 2 (2) 3: 3 (3) 4: 4 (4) 5: a (a) HTH. Derick is correct, you should revert. S

« previous php.doc (#969363871) next »