1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

PHP Array Problems

Discussion in 'PHP' started by ez-designs, Nov 30, 2008.

  1. #1
    I have a text file named ip_array.txt, which contains the following:
    '192.168.1.1', '127.0.0.1', '72.65.2.1'
    Code (markup):
    I'm trying to place the following into an array using the following code:
    
    $fh = fopen('ip_array.txt', 'r');
    $ip_array = array(fgets($fh));
    fclose($fh);
    
    print_r ($ip_array);
    PHP:
    the output is:
    Array ( [0] => '192.168.1.1', '127.0.0.1', '72.65.2.1' ) 
    HTML:
    Which is not what I want.

    I want something like the following:

    $ip_array = array('192.168.1.1', '127.0.0.1', '72.65.2.1');
    print_r ($ip_array);
    PHP:
    which outputs the following

    Array ( [0] => 192.168.1.1 [1] => 127.0.0.1 [2] => 72.65.2.1 )
    HTML:
    How would I get it to store the contents from the text file into an array so that it outputs what's on the second example?

    Thanks beforehand!
     
    ez-designs, Nov 30, 2008 IP
  2. JBrace1990

    JBrace1990 Peon

    Messages:
    20
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    
    $fh = fopen('ip_array.txt', 'r');
    $ip_array = array(fgets($fh));
    fclose($fh);
    $ip_array = explode(",", $ip_array); //explodes into an array
    //it seperates the string by any and all commas
    
    print_r ($ip_array);
    
    Code (php):
     
    JBrace1990, Nov 30, 2008 IP
  3. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #3
    You'll have a much easier time if you store entries on new lines instead of the format you have.

    192.168.1.1
    127.0.0.1
    72.65.2.1
    Code (markup):
    Then getting your array is as simple as this,

    $my_array = file('ip_array.txt');
    Code (markup):
     
    joebert, Nov 30, 2008 IP
  4. ez-designs

    ez-designs Well-Known Member

    Messages:
    230
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    105
    #4
    jBrace you were right on, but joebert's code is more like what i wanted.

    Thanks to both!
     
    ez-designs, Nov 30, 2008 IP
  5. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #5
    Be sure to trim($my_array[$i]) before using it, the newlines are still going to be attached to the end of each array element.
     
    joebert, Nov 30, 2008 IP