0

I have a javascript for a usage graph , the data for the graph within the javascript is defined as follow:

data: [1,2,3,4,5,6],

I have before the javascript a foreach and a value that im trying to use in this data field as follow :

data: [],

Now if i just do echo "$test"; outside javascript on the page i get the following output 1,2,3,4,5,6, which is correct , if i copy this output and use it directly in the datafield it works BUT when I try to call the $test value within the datafield it does not work. So in short

data: [1,2,3,4,5,6], (WORKS)
data: [<?php echo "$test"; ?>], (does not work even though when doing normal echo outside java it does print 1,2,3,4,5,6

Any help would be appreciated

foreach ($chart->usage->days->day as $day): 
$totals = $day->total;
$datau = Round(("$totals") / (1024 * 1024 * 1024), 2);
$test = "$datau, ";
13
  • do you have an extra comma in the $test variable? for example [1,2,3,4,5,6,] ? Commented Mar 27, 2013 at 23:23
  • [1,2,3,4,5,6] isn't the same of ["1,2,3,4,5,6"] Commented Mar 27, 2013 at 23:24
  • yes i do , but even if i copy that and input into the data field it works , example data: [1,2,3,4,5,6,], (works aswel) Commented Mar 27, 2013 at 23:25
  • try to trim the extra comma, some browsers don't like it, try [<?php echo trim($test, ','); ?>] Commented Mar 27, 2013 at 23:25
  • Trailing commas are valid per ES5 spec (only fails in IE7 and below). Commented Mar 27, 2013 at 23:26

1 Answer 1

1

Try doing

$test="1,2,3,4,5,6"; //Make sure to remove a trailing comma.
data: [<?php echo $test; ?>]

I don't see any need for the "$test".

Sidenote: You can take out the echo as well. Also, since data is an array, I would store $test as an array as well.

$test=array(1,2,3,4,5,6);
data: [<?= implode(",", $test) ?>]

This looks cleaner in my opinion.

Edit: Based on your foreach, please try:

$test=array();
foreach ($chart->usage->days->day as $day){
$totals = $day->total;
$test[] = round(($totals) / (1024 * 1024 * 1024), 2);
}

data: [<?= implode(",", $test) ?>],
Sign up to request clarification or add additional context in comments.

10 Comments

String interpolation would have the same output as far as I can see.
but it shouldn't matter, should give the same output
Can you tell me what var_dump($test) looks like?
cant do like that , ive updated my question with my foreach , maybe it will be more clear
Okay I kind of see...but why can't you just var_dump the variable to make sure you have the right output?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.