1

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;
0

5 Answers 5

4

To output a string:

echo implode(', ', $numbers);

for debugging purposes use print_r or var_dump.

Sign up to request clarification or add additional context in comments.

2 Comments

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

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 :)

Comments

1

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

2 Comments

Thanks, this worked great. Should I always do this when outputting array data? (but not always using the $key)
@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.
0

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 );

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.