6 December 2010

Examples of parsing array values on screen. Some examples for beginners.

Array content:

If you have an array, but you don't know what does it contain then you can use print_r() function. The function displays information about a variable in a way that's readable by humans.

Echo array:

If you have the most basic array you can use foreach to echo it. You can also echo key names.
Source code viewer
  1. // First example:
  2. $a = array ('a', 'b', 'c', 'd');
  3. foreach ($a as $var)
  4. echo $var;
  5. // Result: abcd
  6.  
  7. // Second example:
  8. $a = array('key1' => 'a', 'key2' => 'b', 'key3' => 'c', 'key4' => 'd');
  9. foreach ($a as key => $var)
  10. echo 'key: '.$key.' value: '.$var.'<br />';
  11. // Result in parsed html will be:
  12. // key: key1 value: a
  13. // key: key2 value: b
  14. // key: key3 value: c
  15. // key: key4 value: d
Programming Language: PHP

Echo array as list:

You can also create lists out of arrays. Example code:
Source code viewer
  1. $a = array ('a', 'b', 'c', 'd');
  2.  
  3. echo '<ul>';
  4. foreach ($a as $var)
  5. echo '<li>'.$var.'</li>';
  6. echo '</ul>';
Programming Language: PHP
Result:
  • a
  • b
  • c
  • d