Re: Explode-update-implode not working
| From: | Andrew Ballard | Date: | Tue, 23 Jun 2009 16:24:36 +0000 |
| Subject: | Re: Explode-update-implode not working | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-294460@lists.php.net to get a copy of this message | ||
On Tue, Jun 23, 2009 at 12:11 PM, Bob McConnell<rvm@cbord.com> wrote:
> At least not the way I expected it to. Apparently I am doing something
> wrong, but I can't find anything specific that explains it. This is in
> PHP 5.2.6.
>
> Here is the sequence I am trying to implement without the database
> portion. (This is typed in since the VNC I am using doesn't support
> pasting from a Linux client to a MS-Windows server.)
>
> -------------------------------------
> $buff = "key1|value1~key2|value2";
>
> $lines = explode ("~", $buff);
>
> foreach ($lines as $kvpair) {
> $line = explode ("|", $kvpair);
> if ($line[0] == "key1") {
> $line[1] = "value3";
> $kvpair = implode ("|", $line);
> break;
> }
> }
> $newbuff = implode ("~", $lines);
> -------------------------------------
>
> $kvpair is modified, but that change is ignored by implode() with
> $newbuff still containing "key1|value1".
>
> So why doesn't the change to $kvpair get brought in by implode? What
> should I do to update that value?
>
> Bob McConnell
>
See the second note at
http://www.php.net/manual/en/control-structures.foreach.php
Either of these should do what you want:
<?php
$buff = "key1|value1~key2|value2";
$lines = explode ("~", $buff);
foreach ($lines as &$kvpair) {
$line = explode ("|", $kvpair);
if ($line[0] == "key1") {
$line[1] = "value3";
$kvpair = implode ("|", $line);
break;
}
}
$newbuff = implode ("~", $lines);
?>
<?php
$buff = "key1|value1~key2|value2";
$lines = explode ("~", $buff);
foreach ($lines as $key => $kvpair) {
$line = explode ("|", $kvpair);
if ($line[0] == "key1") {
$line[1] = "value3";
$lines[$key] = implode ("|", $line);
break;
}
}
$newbuff = implode ("~", $lines);
?>
Andrew