Creating A JavaScript Array Dynamically Via PHP

March 20th, 2008 by Stephen Cronin (2,967 views)

If you use PHP to create web pages, there may be times when you need to create a JavaScript array dynamically from a PHP array. This is not hard to do, but there is a trap you need to be careful of: dealing with arrays containing only a single element.

NOTE: I have temporarily disabled my code snippet plugin due to an incompatibility with previous code posted on this site. You can read the code below, but it doesn’t look pretty! I’ll rectify this in the coming days.

This post is for the PHP coders out there. If you don’t write code, it may not be for you.

My Original Solution

When writing the LocalCurrency WordPress plugin, I had a PHP array containing values that needed to be converted. The plugin uses AJAX techniques to do the conversions after the page has loaded, so it doesn’t slow down page load times waiting for Yahoo! Finance. The JavaScript to do this needed to access the information in the PHP array.

I decided the best way to implement this was to create a JavaScript array from the PHP array. I came up with the following code:


// create script string to append to content. First create the value array in JavaScript.
$script = $script . "\n" . '<script type="text/javascript"> '. "\nvar lcValues = new Array(";
foreach ($lc_values as $key => $value){
if ($key < (count($lc_values)-1)){
$script = $script . $value . ',';
}
else {
$script = $script . $value . ");\n";
}
}

Note: I’m not echoing the script directly. I’m appending it to a string variable, which itself will be appended to the end of the post content.

This code will create a JavaScript array and populate it with values from a PHP array called $lc_values, which has been created elsewhere. If $lc_values contains the values 25, 34 and 16 (with keys 0, 1 and 2 respectively), then the above code will create the following JavaScript:

var lcValues = new Array(25,34,16);

Great! This is just what I want. A JavaScript array containing the 3 values will be created, and I can use it to convert the values via JavaScript.

The Problem - Arrays With A Single Element

The problem occurs when there is only one value to convert. For example, if $lc_values only contains 25, this will create:

var lcValues = new Array(25);

JavaScript will see this as an instruction to create an array with 25 elements, rather than an array with one element with a value of 25. Later, when you try to access lcValues[0], it will be undefined and will return NaN (Not a Number) when you try to use it.

You cannot use new Array() to create an array with a single numeric element.

The Solution

I got around this problem by checking the number of elements in the PHP array, using the count function. If there is more than one element, it will create the same JavaScript as the original code did. If there is only a single element (for example, 25), it will create the follow JavaScript:


var lcValues = new Array(1);
lcValues[0]=25;

The final code I used looks like this:


// create script string to append to content. First create the value array in JavaScript.
$script = $script . "\n" . '<script type="text/javascript"> '. "\nvar lcValues = new Array(";
if (count($lc_values)>1) {
foreach ($lc_values as $key => $value){
if ($key < (count($lc_values)-1)){
$script = $script . $value . ',';
}
else {
$script = $script . $value . ");\n";
}
}
}
else { // can't create an array that just has one integer element using Array()
$script = $script . "1);\nlcValues[0]=" . $lc_values[0] . ";\n";
}

Note: I can safely use else, because of code outside the above snippet, ensuring the PHP array will have at least one element at this point. You may need to be careful about this. If it’s possible that your PHP array may be empty, consider using elseif (count($phparrayname)==1) instead.

Final Thoughts

There are obviously different ways to do this, but this is what works for me. If it helps anyone else, great! If anyone knows a better way to do this, let me know in the comments.

Subscribe To Site:
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • StumbleUpon
  • PlugIM
  • Sphinn
  • Digg
  • del.icio.us
  • Netvouz
  • MisterWong
  • Bumpzee
  • Reddit
  • Technorati
  • co.mments
Related posts

Tags: , ,

4 Comments

  1. Didn’t know where to post this but, i would like to thanked the admin for helping me solve my RSS Feeds problem. Admin was very helpful and patient as well. So once again, thanks to Stephen. And for those who are looking for help, trust me, Stephen will always be there for you. :)

    Thanks bro!

  2. This is exactly the problem I faced last month in class. Too bad I didn’t know back then that it could be dealt with in such a simple and elegant manner. My code looks like Frankenstein’s monster compared to this :)
    Kudos to you sir!

  3. And string escaping is the other nasty part since most arrays I’ve had to use cgi trough JS are actually strings. Quotes are the main problem with escaping and I find it best to replce them with character codes for JS.

  4. Hi All,

    Thanks for your comments…

Leave a comment

Rules: Leave your name! Enter YourName@YourKeywords and KeywordLuv will use YourKeywords as the anchor text. No inappropriate or offensive comments. No links to inappropriate or offensive sites. Comments must contribute to the discussion.

KeywordLuv

This site uses KeywordLuv. Enter YourName@YourKeywords in the Name field to take advantage.


WordPress Plugins by Stephen Cronin
DualFeeds: Offer both full text & summary feeds. Let your readers choose!
IFrameWidgets: Stop slow javascript widgets breaking your page layout!
FeedEntryHeader: Add a copyright statement to the TOP of your feed!
LocalCurrency: Show currency values to readers in their own currency!
KeywordLuv: Reward your commentators with keyword rich anchor text!