Creating A JavaScript Array Dynamically Via PHP

March 20th, 2008 by Stephen Cronin (20,073 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.

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:
  • Twitter
  • Sphinn
  • DZone
  • Design Float
  • del.icio.us
  • StumbleUpon
  • LinkedIn
  • Tumblr
  • Posterous
  • Digg
  • Facebook
  • Reddit
Related posts

Tags: , ,

18 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…

  5. I was looking for this!
    Thanks I just couldn’t get it to work via php.

    thanks
    Ashley.

  6. UK Links Directory Says:
     (Reply)

    I’m pretty new to web development and I’ve really struggles to get to grips with Javascript on my sites so far. Cheers for your thoughts and ideas, keep em coming!

    LINK REMOVED: because of failure to use KeywordLuv syntax (name@keywords)

  7. Thanks for the help on this . I am sure it will come in useful soon with my php projects.

  8. I have to throw this in there..

    PHP has a function for creating json from php objects, json_encode

    http://us2.php.net/json_encode

    1. I was about to post this and I agree. This page’s script could be turned into a one liner of .

      Since JSON is a subset of JavaScript, JavaScript will already know that it is an array.

  9. Issaac, don’t forget that this function appeared in PHP5, moreover PHP must be higher then 5.2.0. Many people use stll PHP 4.x

  10. Why I am not a programmer: I would have padded it with the size of the array, so your first one would have been Array(3,25,34,16), and your second one Array(1,25).
    I don’t create theory, I get things outta the ditch.
    ;-)

  11. Thanks i want to try the local currency plugin and your code will make it alot easier. Seems like you figured out the bugs for everyone already.

  12. I am so glad I found this! I have been having issues with something similar in another project and was going to outsource it but I’m going to giver this a try first to see if it fixes the issue – thanks again!

  13. Thanks for this. The neat handling of single-element arrays is great :)

    Previously, I init. js arrays using the syntax:

    var lcValues = new Array(25);

    lcValues[1]=’hello’;
    lcValues[2]=’goodbye’;

    but the init format of:
    var lcValues = new Array(’hello’,'goodbye’);
    is a lot cleaner.

  14. This will definitely come in handy for me later. I have bookmarked this page =] I especially like anything that utilizes AJAX due to the decreased load, but I haven’t been in a situation where I really needed to create something like this yet. Thanks for the tips!

  15. Wow! great coding. Keep up the good work.

  16. This is what I was looking for, thank you!

  17. Cheers mate, saved me lots of time trying to get my head around that one :)

Leave a comment

THIS BLOG IS NO LONGER DOFOLLOW

Rules: Leave your name! No inappropriate or offensive comments. No links to inappropriate or offensive sites. Comments must contribute to the discussion.


Get your ad shown hereGet your ad shown hereWPVote - Digg for WordPress Lovers Advertise

WordPress Plugins by Stephen Cronin

Want a Custom WordPress plugin? See my Services page.

Greasemonkey Scripts by Stephen Cronin

Visit my home page at Userscripts.org.