Creating A JavaScript Array Dynamically Via PHP

March 20th, 2008 by Stephen Cronin (Please wait) [Shortlink]

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.

Like this article? Plus One it!

Tags: , ,

There are 11 reponses to this article. Visit the comments page.

Leave a Reply

Anti-Spam Quiz:


Stephen Cronin

Stephen Cronin is Manager of Online Service Delivery at a Queensland Government department & has been a freelance WordPress developer/consultant since 2007
*Content on this site is my own and is not related to my employer

Hire me - I'm expensive, but I'm very good!

WordPress Plugins

Want a Custom WordPress plugin? See my Services page.

Greasemonkey Scripts

Visit my home page at Userscripts.org.