Friday, August 2, 2002, 11:29:39 PM, you wrote:
JV> Tried to post this to the news group before, but I'm having trouble getting
JV> to my news server from work - hopefully I'm not posting a duplicate.

JV> I think I'm seeing the problem I'm seeing because I'm getting a copy of a
JV> var instead of a reference to it, but I'm not sure the best we to get around
JV> this problem.

JV> In my little sample script, I've got an array of objects.  When I use
JV> foreach to loop through the array and make a change to an item, it doesn't
JV> change the object in the array, just the var that I have while I'm in the
JV> foreach loop.

JV> What's the right way to loop through this array if I really want to change
JV> homer's name to marge in this example?  The way it is now, I see my echo
JV> saying that I'm changing the name, but when I do the second var_dump, it's
JV> the same as the first var_dump.

JV> Thanks in advance,
JV>    Jesse

JV> <?php

JV>     class Name {
JV>         var $firstName;
JV>         var $lastName;

JV>         function Name($first, $last) {
JV>             $this->firstName = $first;
JV>             $this->lastName = $last;
JV>         }
JV>     }

JV>     $names[] = new Name("joe", "shmo");
JV>     $names[] = new Name("billy", "bob");
JV>     $names[] = new Name("homer", "simpson");


JV> <html>
JV>     <body>
JV>         <?php echo var_dump($names) ?>
JV>         <br>
JV>         <?php
JV>             foreach ($names as $name) {
JV>                 if (strcmp($name->firstName, "homer") == 0) {
JV>                     echo "changing homer to marge<br>";
JV>                     $name->firstName = "marge";
JV>                     break;
JV>                 }
JV>             }
JV>         ?>
JV>         <?php echo var_dump($names) ?>

JV>         <br>
JV>     </body>
JV> </html>

This should work:

foreach ($names as $key=>$val) {
        if (strcmp($val->firstName, "homer") == 0) {
                echo "changing homer to marge<br>";
                $names[$key]->firstName = "marge";


PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to