PHP4 limitation- cannot do foreach by reference
This currently slightly ugly code in the function cmt_get_hierarchies() is required because PHP4 can't handle references in a foreach:
<pre>
reset($hierachies);
while (list($key, $value) = each($hierarchies)) {
$hierarchy =& $hierarchies[$key];
array_reverse($hierarchy);
}
</pre>
For PHP5 only it will be possible to do this-- so save this page for upgrading to Drupal 6!
<pre>
foreach($hierarchies AS &$hierarchy) {
array_reverse($hierarchy);
}
</pre>
From http://us2.php.net/foreach
joaohbruni at yahoo dot com dot br
25-Jan-2007 01:24
Iterate through an array of objects, and change property values from original object.My original code only worked in PHP5:
foreach($array as $element) {
$element->property = "new_value";
}Solution for both PHP4 and PHP5:
reset($array);
while (list($key, $value) = each($array)) {
$element =& $array[$key];
$element->property = "new_value";
}
This currently slightly ugly code in the function cmt_get_hierarchies() is required because PHP4 can't handle references in a foreach:
<pre>
reset($hierachies);
while (list($key, $value) = each($hierarchies)) {
$hierarchy =& $hierarchies[$key];
array_reverse($hierarchy);
}
</pre>
For PHP5 only it will be possible to do this-- so save this page for upgrading to Drupal 6!
<pre>
foreach($hierarchies AS &$hierarchy) {
array_reverse($hierarchy);
}
</pre>
From http://us2.php.net/foreach
joaohbruni at yahoo dot com dot br
25-Jan-2007 01:24
Iterate through an array of objects, and change property values from original object.My original code only worked in PHP5:
foreach($array as $element) {
$element->property = "new_value";
}Solution for both PHP4 and PHP5:
reset($array);
while (list($key, $value) = each($array)) {
$element =& $array[$key];
$element->property = "new_value";
}
Comments
Bah, it didn't work at
Bah, it didn't work at all:
<pre>// this can be cleaned up for Drupal 6 when PHP4 compatibility is dropped:
reset($hierarchies);
while (list($key, $value) = each($hierarchies)) {
$hierarchy = &$hierarchies[$key];
array_reverse($hierarchy);
}
</pre>
Due to "syntax error, unexpected T_VARIABLE" on the $hierarchy = ... line.
So we'll just go through the thing with a for loop, eh?
<pre>
$c = count($hierarchies);
for($i=0;$i<$c;$i++) {
$hierarchies[$i] = array_reverse($hierarchies[$i]);
}
</pre>
Post new comment