Outputing php variable in javascript

ensodevensodev Posts: 65

Passing PHP Arrays to JavaScript
PHP provides two functions that can be used to pass arrays to JavaScript: implode and json_encode. The implode function can only be used with single-level arrays. This approach is demonstrated below.

The json_encode function is tailor-made for passing arrays; it can be used to pass single-level arrays and multidimensional arrays as well.

Using PHP's implode Function
The PHP implode function can be used on a single-level PHP array consisting of string, number, boolean, or null values to build a string that becomes an array literal in JavaScript. That is, if you have a PHP array ($ar) you can pass it to a JavaScript array as follows:

var ar = <?php echo '["' . implode('", "', $ar) . '"]' ?>;
Here we demonstrate with a numerically indexed array:

<?php // php array $fruits = array('apple', 'orange', 'mango', 'banana', 'strawberry'); ?> // use php implode function to build string for JavaScript array literal var fruits = <?php echo '["' . implode('", "', $fruits) . '"]' ?>; // ["apple", "orange", "mango", "banana", "strawberry"]

You can use implode to pass the keys and values of an associative array separately:

<?php $book = array( // associative array "title" => "JavaScript: The Definitive Guide", "author" => "David Flanagan", "edition" => 6 ); // can build string here instead of in script tags if you like $book_keys = '["' . implode('", "', array_keys($book) ) . '"]'; ?> var book_keys = <?php echo $book_keys; ?>; // output php string here // ["title", "author", "edition"]; var book = <?php echo '["' . implode('", "', $book) . '"]'; ?>; // ["JavaScript: The Definitive Guide", "David Flanagan", "6"];

The square brackets surrounding the output of implode in PHP are used to form the array literal in JavaScript. The quotes enclosing the array values are necessary to avoid JavaScript errors, but they have the unfortunate consequence of converting any boolean or numeric values to strings.

You can avoid this problem by using PHP's json_encode function rather than implode to prepare the PHP array for passage to JavaScript.

Note:- Copied


Sign In or Register to comment.