Jump to content

Retrieving array values.


fortnox007

Recommended Posts

Hi All, small question here. I was just playing around with a small script I made to obtain an ip-address, remove the dots and than glue the parts together. Not for any use but for practice. But I am having difficulties to accessing the array values. But maybe that because its the first time i am using explode() and print_r. If someone has a spare minute I would be pleased to be enlightened.

 

<?php
             $ip=$_SERVER['REMOTE_ADDR'];
             echo $ip.'<br />';
             $cleaned_ip = substr($ip,0,6);
             echo $cleaned_ip.'<br />';
             $cleaned_ip2 = print_r(explode('.', $ip, 6)).'<br />';
             // this is the point where I dont know how to get the array values.
             // echo $cleaned_ip2[0].[1].[2];   that doesnt work. ;(
         ?>

Link to comment
https://forums.phpfreaks.com/topic/211750-retrieving-array-values/
Share on other sites

Run this, it's the same thing, but it'll look cleaner. I'll then explain how the array would look.

 

<?php
   $ip = '192.168.0.1'; // Just an example IP address.
   echo 'Your IP address is: ' . $ip . '<br />';

   // Now let's create an array by exploding the IP by the peroids
   $array = explode('.', $ip); // I'm not sure why you were provided a limit of 6

   // This will display the preformatted array, so its easier to read.
   echo '<pre>', print_r($array), '</pre>';

   // And now echo the first element.
   echo $array[0]; // will echo 192
?>

 

The resulting array from exploding the IP address would look something like this:

Array (
     [0] => 192
     [1] => 168
     [2] => 0
     [3] => 1
) 1

 

So $array[2] would hold the value 0, $array[1] would hold 168.

 

Now, to join the array together you can do it manually.

$joined = $array[0] . $array[1] . $array[2] . $array[3];

 

Or you can use implode to save you the hassle.

$joined = implode('', $array);

 

Good luck.

ProjectFear & nethnet Thank you both for you wicked fast replies and teaching. If you were chicks I would marry you both ;-)

 

Thanks also for the more inside of the of things. I still need to learn alot but this site helps alot.

@ProjextFear: I provided the limit of 6 because I read an article about how phpnuke uses a first part of the ipaddress to verify the user and prevent session hijacking. So I thought how would they have split the address up in parts... and so I ended up with these functions. But your way is nicer ;) And above all a nice way to understand arrays better.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.