tags:

views:

56

answers:

5

I want to create an array of numbers: 10, 9,8...to 1. But when I echo $numbers, I get "Array" as the output as to the numbers.

There is probably a simple thing I missed, can you please tell me. thanks!

$numbers=array();
for ($i=10; $i>0; $i--){
    array_push($numbers, $i);
}
echo $numbers;
+4  A: 

To output a string:

echo implode(', ', $numbers);

for debugging purposes use print_r or var_dump.

SilentGhost
Thank you! It works now. Should I always include the implode function to output strings?
ggfan
@ggfan: You may want to read the `implode` docu to get to know what it actually does: http://php.net/manual/en/function.implode.php
Felix Kling
+1  A: 

No you are not missing anything. Of course $numbers is an array.
If you do print_r($numbers) than you see what elements are in the array.

It very much depends what you want to do with array in the end. You can for example also loop over the array values:

foreach($numbers as $number) {
    //whatever you want to do
    echo $number;
}

If you only want to print theses 10 numbers you can also just do:

for ($i=10; $i>0; $i--){
   echo $i;
}

As I said it depends on what you want to do :)

Felix Kling
+1  A: 

Depends on what you want the output to look like.

For debugging purposes, this should work:

print_r($numbers);

For a "prettier" output:

foreach ($numbers as $key => $value)
    echo $key . "=" . $value
Stargazer712
Thanks, this worked great. Should I always do this when outputting array data? (but not always using the $key)
ggfan
@ggfan: It depends what the output should look like. There is no general rule. But by using a for(each) loop you can iterate over the array and have access to the single elements.
Felix Kling
A: 

First of all, you can create that array much easier using range()

$numbers = range( 10, 1 );

Secondly, only scalars can be echoed directly - complex values like objects and arrays are casted to strings prior to this. The string cast of an array is always "Array".

If you want to see the values, you have to flatten the array somehow, to which you have several options - implode() might be what you're looking for.

echo implode( ',', $numbers );
Peter Bailey
A: 

For debugging purposes you might like:

echo '<pre>' . print_r($numbers, true) . '</pre>';

As it's output is clear without having to look at page source.

Thead D. Icted