note 3587 deleted from function.sizeof by jimw
| From: | jimw@php.net | Date: | Wed, 03 Apr 2002 18:58:30 +0000 |
| Subject: | note 3587 deleted from function.sizeof by jimw | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-28562@lists.php.net to get a copy of this message | ||
Remember, PHP code is interpreted so sizeof() is always evaluated in place and everytime. So a very
simple code like below can blow up your server box (tested :)
<?
$arr= range(0,19);
echo sizeof($arr)."<BR>";
for($i=0; $i<=sizeof($arr); $i++) {
// <= is used intentionally
$arr[$i] = "";
echo sizeof($arr)." Passing over #".$i."<BR>\n";
}
?>
The assignment $arr[$i] when used in conjunction with <= in the for loop causes the assignment to
add an extra element to the end of the array. So when the for-condition is next time checked when
$i=20, sizeof($arr) will yield 21, the next time 22, and so on. So the program in fact starts to
leak heavily and very rapidly.
You can instead use:
<?
//...
$c = sizeof($arr);
for($i = 0; $i <= $c; $i++) {
// <= is used intentionally again ...
?>
This one will add the 21th element, but will stop then. No leak at all...