Sunday, March 20, 2011

Convert a PHP Array to a JavaScript Array

Many times when working with advanced web applications it may be necessary to convert an array of PHP variables into an array of JavaScript variables. I stumbled upon this issue in some recent web development work and most of the solutions online seemed incredibly complicated for such a simple task.

JavaScript is different than PHP because JavaScript allows manipulation of the page data on the client side (meaning no page refreshes are necessary). PHP works by sending information to a server (server side) to manipulate and return. This means that page refreshes are necessary (typically). So let's say you have an array of strings in PHP; we'll call it "phpArray()". This array may be created in PHP with the following PHP code:

$phpArray = array("Word One", "Word Two", "Word Three", "Word Four");

Now we have a $phpArray variable in PHP that contains the words as strings. To convert this array to a JavaScript array, we are going to first create a string from the PHP array by running through a PHP loop. First, we will declare a string variable in PHP to hold the loop's contents:

$string = ""

Now we're going to loop through the loop and add each element of the array to the string with quotes around it. (Note: this is for an array of strings. An array of ints should be handled as strings in PHP, but passed to JavaScript without the quotes.)

foreach ($phpArray as $a) {
$string .= "\"" . $a . "\", ";

This code creates a PHP string that looks like:

$string = "Word One", "Word Two", "Word Three", "Word Four",

Now, we need to do one final thing. This code loops through the array and adds a comma (,) and space( ) to the end of each array element. That means that the resulting code will appear as "Last Word", We don't want this because it will mess up our JavaScript. To cut off this last comma and space, we will do:

$finalstring = substr($string, 0, (strlen($string) - 2));

This code removes the last comma and allows us to place it into our JavaScript. In the JavaScript section of our page, we're now going to add:

<script language="javascript" type="text/javascript">
            var jsString = new Array(<?php echo $finalstring; ?>);

We now have a JavaScript array called "jsString" which contains all of the elements of the PHP string array. It would be the same as writing:

var jsString = new Array("Word One", "Word Two", "Word Three", "Word Four");

That's all there is to it. If you have any questions, just leave a comment!