Re: Does passing an uninitialized array variable initialize it? (PHP 5)
- From: Rik <luiheidsgoeroe@xxxxxxxxxxx>
- Date: Mon, 30 Jul 2007 23:27:10 +0200
On Mon, 30 Jul 2007 22:56:19 +0200, <google2006@xxxxxxxxxxxxxxxx> wrote:
The following code never sees the end of the array, and generates an
out of memory error under PHP5 (both CLI and Apache module) :
while (isset($rank[$i])) {
$rank[$i] = trim($rank[$i++]);
}
Moving the post increment to a separate line fixes this issue:
while (isset($rank[$i])) {
$rank[$i] = trim($rank[$i]);
$i++;
}
For some reason PHP5 appears to be initializing $rank[($i+1)] each
time, perhaps because it's passing the value to trim(). The subsequent
isset() test on that element succeeds so the loop continues
indefinitely as each new element is initialized.
Hmmz, this test says it doesn't (PHP 5):
<?php
$arr = array();
$i = 0;
trim($arr[$i++]);
var_dump($arr);
?>
Result (without obvious notices):
array(0) {
}
If it works for you, it seems to me they fixed something in PHP5 that did not work as _I_ would expect in PHP4: it seems $i on the left-hand side is evaluated _after_ the running of the right hand side in PHP5, and _before_ in PHP4, which this example shows: it overwrites the variables present:
<?php
echo phpversion();
$arr = array(1,2,3,4);
$i=0;
$save = 0;
while (isset($arr[$i])) {
$arr[$i] = trim($arr[$i++]);
if(++$save > 5) break;
}
var_dump($arr);
?>
Output:
5.2.2array(7) {
[0]=>
int(1)
[1]=>
string(1) "1"
[2]=>
string(1) "1"
[3]=>
string(1) "1"
[4]=>
string(1) "1"
[5]=>
string(1) "1"
[6]=>
string(1) "1"
}
I'm a bit struggling for words here, but see it as this: finding the reference to which to couple the output of your code happens after evaluating in PHP5, in PHP4 it first determines what the actual target is.
I have no idea where to start finding when and how this behaviour changed, but I bet that handling references somewhat differently has something to do with it.
--
Rik Wasmus
.
- Follow-Ups:
- References:
- Does passing an uninitialized array variable initialize it? (PHP 5)
- From: google2006
- Does passing an uninitialized array variable initialize it? (PHP 5)
- Prev by Date: Re: Does passing an uninitialized array variable initialize it? (PHP 5)
- Next by Date: Re: Does passing an uninitialized array variable initialize it? (PHP 5)
- Previous by thread: Re: Does passing an uninitialized array variable initialize it? (PHP 5)
- Next by thread: Re: Does passing an uninitialized array variable initialize it? (PHP 5)
- Index(es):
Relevant Pages
|