Page 1 of 1

Changing values in multidimensional associateive array

Posted: Thu Aug 17, 2006 4:18 am
by mahr
JayBird | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


I have some problem with changing values in associative array:

My example

Code: Select all

foreach ($tableCSV as $row){
                                foreach ($row as $int=>$value){

                                        $row[$int] = str_replace("\xb9","\xc5\xa1",$value);
                                        print_r($row[$int]);
                                }
                      }

print("<PRE>");
print_r($tableCSV);
print("<PRE>");
It works right (at least inner loop) but end results (changed values) in $tabelaCSV are not saved.
Any help will be really appreciated:)


JayBird | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Thu Aug 17, 2006 4:20 am
by mahr
Sorry to forget put code tags.

PS: I have PHP 4.3 so I can not assign value by reference

Posted: Thu Aug 17, 2006 5:39 am
by Jenk

Code: Select all

<?php

$tableCSV = array(array(1,2), array(3,4), array(4,5));

foreach ($tableCSV as $key => $row){
    foreach ($row as $int => $value){
        $tableCSV[$key][$int] = str_replace("\xb9","\xc5\xa1",$value);
        print_r($row[$int]);
    }
}
print("<PRE>");
print_r($tableCSV);
print("<PRE>");
?>

Posted: Thu Aug 17, 2006 6:32 am
by georgeoc
The reason for this is that a foreach loop in PHP4 will run on a copy of the array, rather than the original. So in the second foreach in your example, the variable $row no longer has any link to the variable $tableCSV.

Therefore, Jenk is correct to replace this code:

Code: Select all

$row[$int] = str_replace("\xb9","\xc5\xa1",$value);
with this:

Code: Select all

$tableCSV[$key][$int] = str_replace("\xb9","\xc5\xa1",$value);
Have a look at the manual: http://www.php.net/foreach.

Posted: Thu Aug 17, 2006 7:36 am
by mahr
Thank you guys!

I have just solved my problem with some not really elegant method. Now I am going to change with your "elegant" method as you suggest :D
Thanks again!