0

How do I append elements to an array within a loop? For example, I am using a library to render a graph.

I wish to add values to the graph like so:

$data = array();

for ($x=0; $x<=50; $x++)
{
    $data["00:".x] = rand(-10, 30);
}

So in theory I should have the elements "00:00", "00:01", "00:02" etc. all with a random number as their value. However, the library does not then render the graph.

I'm guessing it's because I don't understand PHP enough. How do I go about trying to achieve this?

2
  • 1
    You should add error_reporting(-1); to enable proper debugging; also consider adding var_dump($data); to see where things went wrong. Commented Feb 1, 2014 at 2:01
  • I did not know about those, thanks. Commented Feb 1, 2014 at 2:03

1 Answer 1

3

You're missing the leading zeros for values of $x 0 through 9. You're also missing the dollar sign before your variable $x:

for ($x=0; $x<=50; $x++)
{
    $data["00:".str_pad($x, 2, "0", STR_PAD_LEFT)] = rand(-10, 30);
}
Sign up to request clarification or add additional context in comments.

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.