Hi, If I have some code in php5 foreach( $a as &$b ) { $b = /*what ever*/ } Code (markup): Is is correct to say that In php4 this is functionally the same as above. foreach( $a as $key => $b ) { $a[$key] = /*what ever*/ } Code (markup): Or are there some fundamental differences that I am missing? Thanks FFMG
// Initialize limit outside loop $size = sizeof($a); // Loop for ( $i=0; $i<$size; $i++ ){ $a[$i] = /*what ever*/; } PHP: Bobby
Thanks, but this will clearly not work in most cases. Try: $a = array( 'a'=>'a1', 'b'=>'b1' ); $size = sizeof($a); // Loop for ( $i=0; $i<$size; $i++ ){ $a[$i] = /*what ever*/; // Notice: Undefined offset: xxx } PHP: Your example will only work where it is a numbered array(). Furthermore, isn't my example shorter _and_ it will work in the example above? Regards, FFMG
The foreach() construct when used in the form $array as $key => $value will produce the same functionality but works by creating a copy of the array and makes all assignments by value. So what does this mean? Basically, you cannot directly modify the values directly as in the referenced PHP5 example. Another major drawback is that there are serious server resource utilization considerations especially if the array is large. Just because your refactored example it is shorter does not mean it is better. It still suffers from the increased server resources issue. To address the associative indexes try something like this: foreach ( array_keys($a) as $index ){ $a[$index] = /* whatever */ ; } PHP: In this case it uses minimally more server resources as it only retrieves the keys. It still allows direct value modification of the parent array. Bobby
I did not know that. Of course, shorter is not better, but your original example only worked in certain numbered arrays. And because it was almost doing the same work I was wondering why the need to give it in the first place. Thanks for the code. FFMG