Creating A JavaScript Array Dynamically Via PHP

Update – 1 August 2013:
There are lots of suggestions in the comments that are better than my original solution. Also, with 5 years of hindsight, I’d approach it differently anyway! The way I’d do this now would be as follows:

<script type="text/javascript">
	var lcValues = <?php echo json_encode($myPHPArray); ?>;
</script>

So much simpler! PHP4 has almost disappeared so there’s no reason not to use json_encode. I’d recommend that you stop reading now and just go with that.

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.

14 responses on “Creating A JavaScript Array Dynamically Via PHP

  1. NikolaD@freeware software

    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.

    1. KnifeySpooney

      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.

  2. Moder@Cellphones & Accessories

    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

    1. Stephen Cronin Post author

      Thanks to everyone who suggested json_encode, but I’m with Moder on this one. When I wrote this (almost 2 years ago), I was trying to avoid a dependence on PHP5.

      Although I use PHP5 for some of my stuff now, I still try to avoid it where possible for anything related to WordPress (which still supports PHP4).

  3. Ben Tremblay

    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.
    ;-)

    1. Stephen Cronin Post author

      Hi Ben,

      Didn’t see your comment there (from over a year ago)!

      Interesting approach! It should work – I can’t see any problem with it – but I’d still stick with an if else statement (or maybe Mike’s implode solution) because … well because the JavaScript is, well, cleaner somehow (I’m not articulating this very well).

      I’m not against workarounds to get something working, but only as a last resort.

  4. Bill@cheap flights

    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.

  5. Mike

    Maybe I’m missing something cause I read it very fast, but this is how I pass a php array of numbers to a javascript array (very tiny, clean and simple):

    var myJavaScriptArray = [<?php echo implode(",",$myPHPArray); ?>];
    

    With php we don’t have to reinvent the wheel. There are a lot of useful built-in functions, like “implode”.

    To make this a little bit more useful… If it’s an array of strings, just do this:

    var myJavaScriptArray = ["<?php echo implode('","',$myPHPArray); ?>"];
    

    Note: For this last one, check if the php array is not empty. Otherwise you will get a javascript array with one empty string.

    Hope it helps :)

    1. Stephen Cronin Post author

      Hi Mike,

      That looks like a neat solution. I’ve used implode a lot in the last year or two, but when I wrote this I wouldn’t have been that familiar with it. I’m still not sure whether I would have thought of this approach, but at least it makes sense to me.

      By the way, I fixed up the code in your first comment and removed the second one. I’ll have to add a way for users to do this easily.

  6. P

    The simple solution would be to NOT use new Array (whose functionality can be modified by other javascript code) but to just pass the values into square brackets. Javascript accepts [#,#,#] as an unmodified raw array object, even [#], which would solve the problem above altogether without fancy hacks or additional instructions.

    Change line 2 part: “\nvar lcValues = new Array(“; to “\nvar lcValues = [“;
    and line 8 part: “);\n”; to “];\n”;

    And problem solved.

  7. Mike

    It’s been quite a lot since I posted the implode solution. Now with json included in php5 and all that, I think the safest and neatest way to go would be something like:

    var myJSArray = ;

    This saves you a lot of trouble mostly for arrays of strings, you don’t need to worry about things like if they include some unexpected quotes and stuff like that, as json takes care of producing a safe ready to use JavaScript syntax for your php objects.

    Enjoy! :)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Anti-Spam Quiz: