Re: problem with join(array, "")
| From: | James Lyon | Date: | Wed, 31 May 2000 14:03:25 +0000 |
| Subject: | Re: problem with join(array, "") | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-717@lists.php.net to get a copy of this message | ||
> I've got the following code which splits an ip address into it's four
> octets:
>
> $octet[4] = strtok($remote_ip, ".");
> for ($i = 3; $i >= 1; $i--) {
> $octet[$i] = strtok(".");
> }
>
> If I add code as follows:
>
> for ($i = 1; $i <= 4; $i++) {
> echo $octet[$1];
> }
>
> it prints the octects in reverse so 192.168.47.8 becomes 847168192. However,
> if I add the following lines:
>
> $revip = join($octet, "");
> echo $revip;
>
> this should join the octet[] array into a string with "" as the separator.
> However, when the output of the next line is not 847168192, it's 192168478.
>
> Anyone know if this is a bug or a feature? Am I misunderstanding something
> here?
I believe all that's happening is that the join() function walks through the
array in the order of its elements without regard to the index used for
accessing individual elements. So, I would guess the following would rectify
your $revip problem...
for ($i=1; $i <= 4; $i++) {
$newarray[$i] = $octet[$i];
}
$revip = join("", $newarray);
echo $revip;
...but I'm not sure this is the best way in any case.
what about the split() function, and so forth ... maybe just drop the "."
characters from your original $remote_ip?
Maybe something ugly but effective like ...
list($a, $b, $c, $d) = split($remote_ip, ".", 4);
$revip = $d . $c . $b . $a;
Or...
$revip = "";
$octet[4] = strtok($remote_ip, ".");
for ($i = 1; $i <= 4; $i++) { // Or use a while, in case partial
address.
$revip .= strtok(".");
}
Hope this helps,
James.