0

I need to transfer the values from a PHP array into a JavaScript array so that it can be used in my application, I have managed to get up to this:

var Descriptions = array(<?php 
                foreach ($tasks as $task) {
                $ID = $task['ID'];
                $description = $task['description'];

                echo $ID . "[" . $description . "]" . ",";  
                }

                ?>);

and it works fine except for one thing: I dont know how to tell PHP to not put a comma after the last array value. The extra comma is causing a syntax error so it breaks my code.

Thanks in advance for any ideas, RayQuang

6 Answers 6

2

The quick and dirty way:

for($i = 0, $c = count($tasks); $i < $c; $i++) {
   $task = $tasks[$i];
   ...
   echo $ID . "[" . $description . "]" . (($i != $c-1) ? "," : ''); 
}

There are obviously other ways of accomplishing this, one way would be to build up a string and then use the trim() function:

$tasks_str = '';
foreach(...) {
   ...
   $tasks_str .= ...
}

echo trim($tasks_str, ',');

Or, (my favorite), you could build up an array and then use implode on it:

$tasks_array = array();
foreach(...) {
   ...
   $tasks_array[] = ...
}

echo implode(',', $tasks_array);
Sign up to request clarification or add additional context in comments.

1 Comment

As i said - this is dangerous, you need to make sure you escape certain characters in the $ID and $description variables before outputting them into a JavaScript block. json_encode already does this for you.
1

don't try to build it manually, use json_encode

1 Comment

I can't understand why you would ever want to use any other method?
1
var Descriptions = <?=json_encode($tasks);?>;

Comments

0
var DescriptionsString = <?php 
            foreach ($tasks as $task) {
            $ID = $task['ID'];
            $description = $task['description'];

            echo $ID . "[" . $description . "]" . ",";  
            }

            ?>;
var Descriptions = DescriptionsString.split(',');

Comments

0

try,

var Descriptions = array(<?php 
                $str = '';
                foreach ($tasks as $task) {
                $ID = $task['ID'];
                $description = $task['description'];

                $str .= $ID . "[" . $description . "]" . ",";  
                }
                 echo trim($str,',');      
                ?>);

Comments

0

Not one to miss out on a trend:

$out = array();
foreach ($tasks as $task) {
    $ID = $task['ID'];
    $description = $task['description'];

    $out[] = $ID . "[" . $description . "]";  
}
echo implode(',', $out);

Using implode().

Comments

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.