>Now that I have a string of colors delimited by commas, I would like to 
>parse the string and print out all my colors.  I have read the 
>documentation on using the list() function but I find it confusing.  Can 
>someone clear the fog from my mind please?

Remember when "deconstructionism" was a hot topic in university circles? 
They would have loved the list() construct. :-)

list() is basically just an array de-constructor:

<?php
  $array = array('a', 'b', 'c');
  list($a, $b, $c) = $array;
  echo 'a is $a, b is $b, c is $c<BR>\n";
?>

In other words, list tears apart an array and gets the values out, stuffs
the values into the variables you provide, and throws away the keys (aka
indices) from the array.

list() is most commonly used with each() and with mysql_fetch_row (and
similar).

Now, each() can be a bit confusing, since it tears through an array,
building tiny little arrays of the key/value in it as it goes.  Let's watch
this in "slow-motion":

<?php
  $array = array('a', 'b', 'c');
  echo "array is ";
  var_dump($array);
  echo "<BR>\n<BR>\n";
  while ($element = each($array)){
    echo "A single key/value pair in array gets converted by 'each()' into:
";
    var_dump($element);
    echo "<BR>\n<BR>\n";
    echo "Note that it is the each() that builds up this somewhat odd array
for list to deconstruct.<BR>\n<BR>\n";
    echo "Then list(\$key, \$value) = \$element gives you: ";
    list($key, $value) = $element;
    echo "$key, $value<BR>\n";
  }
?>

Normally, of course, you just do:

<?php
  $array = array('a', 'b', 'c');
  while (list($key, $value) = each($array)){
    echo "$key, $value<BR>\n";
  }
?>

Now, when you use mysql_fetch_row(), which returns an array, the list()
construct is just tearing that apart into its values:
<?php
  $query = "select * from mytable"; # NEVER use select * in *REAL* code!
  $data = mysql_query($query) or error_log(mysql_error());
  while (list($one, $two, $three) = mysql_fetch_row($data)){
    echo "The first three columns are $one, $two, $three<BR>\n";
  }
?>

-- 
Like Music?  http://l-i-e.com/artists.htm


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to