faqts : Computers : Programming : Languages : PHP

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

37 of 38 people (97%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

how can I take a list and make each row a value in an array?

Feb 19th, 2008 22:03
dman, Philip Olson, Techek, Ionized Hydronium, http://www.ttnr.org


If you have a text file that looks like this :
  phil|orange|cow
  joe|green|goat
  sam|red|dog
Each line can magically be an element in the array using the PHP file() 
function, like so :
  $lines = file('info.txt');
  print $lines[0]; // phil|orange|cow
  print $lines[1]; // joe|green|goat
  print $lines[2]; // sam|red|dog
Using explode() will help seperate the lines by the seperator, which in 
this case is a '|' , the following will loop through the text file, 
explode each line and print out the given parts.  We're assuming that 
the text file (info.txt) has this format :
  name|color|animal
  name|color|animal
  name|color|animal
  <?php
    $lines = file('info.txt');
    foreach ($lines as $line) {
        $p = explode('|', $line);
        echo $p[0]; // prints name
        echo $p[1]; // prints color
        echo $p[2]; // prints animal
    }
  ?>
In the above, we could replace:
  $p = explode('|', $line);
With:
  list($name, $color, $animal) = explode('|', $line);
To create/define more _friendly_ variables to play with.
Related manual entries are as follows :
  explode -- Split a string by string
    http://www.php.net/manual/function.explode.php
  foreach
    http://www.php.net/manual/control-structures.foreach.php
    http://www.php.net/manual/control-structures.php
  file -- Reads entire file into an array
    http://www.php.net/manual/function.file.php
  II. Array Functions
    http://www.php.net/manual/ref.array.php