Connecting Tech Pros Worldwide Forums | Help | Site Map

Command to Print or Echo all Elements of an Array?

tharden3's Avatar
Site Addict
 
Join Date: Jul 2008
Location: Ocala, FL (United States)
Posts: 817
#1: Jan 3 '09
Is there a quick way to ask to 'echo' or 'print' all elements of a numeric array? Can I specify to print "all of the keys" or "all of the values"? I wrote up 5 quick lines of code to print all of my values, but there has to be a built_in function I can call to do that for me right? Like function($months) or something?
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $months=array('January','February','March','April');
  3. $key=0;
  4. $calendar=count($months);
  5. while($key<=$calendar){
  6. echo "$months[$key]<br/>";
  7. $key++;}
  8. ?>
  9.  
Do I use var_dump()? This would allow me to see the entire thing, but what if I only want to specify 'just keys' or 'just values'?

Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,664
#2: Jan 3 '09

re: Command to Print or Echo all Elements of an Array?


Quote:

Originally Posted by tharden3 View Post

Do I use var_dump()? This would allow me to see the entire thing, but what if I only want to specify 'just keys' or 'just values'?

does it really matter if you see both values? I'm glad for any information I get...

regards
Atli's Avatar
Moderator
 
Join Date: Nov 2006
Location: Iceland
Posts: 3,754
#3: Jan 3 '09

re: Command to Print or Echo all Elements of an Array?


Hi.

You can use print_r to see your array in a formatted way.
I usually just do:
Expand|Select|Wrap|Line Numbers
  1. echo "<pre>", print_r($array, true), "</pre>";
when I need to debug an array in my web pages in a hurry.

If you need to filter or change the array before you show it, one of the Array Functions can most likely do that for you before you print it.

P.S.
Check out the foreach loop
Expand|Select|Wrap|Line Numbers
  1. foreach($months as $month) {
  2.   echo "$month<br />";
  3. }
tharden3's Avatar
Site Addict
 
Join Date: Jul 2008
Location: Ocala, FL (United States)
Posts: 817
#4: Jan 3 '09

re: Command to Print or Echo all Elements of an Array?


Oh, ok. That's like saying, "for x in this, do this". Thanks for the help.
Reply