1

I'm having some troubles trying to iterate over a PHP array inside a Javascript array... I've searched over the forum and, though I found some posts about copying PHP values to Javascript values, I'm unable to find exactly what I'm trying to achieve...

I have a PHP array of arrays called "phpArray", and I want each value of this array to be copied into a Javascript array of arrays (called "javaArray"). I have a Javascript loop that populates the Javascript array when the "phpArray" comes empty, and I'm simply trying to use a PHP index to iterate over the "phpArray". However, it acts as if the PHP index is never increased, and the only array value that I can get is the first one of the "phpArray"... Here is the piece of code corresponding to this:

for (var i = 0; i < javaArray.length; i++) {
    javaArray[i] = new Array(<?php echo $numCols; ?>);

    for (var j = 0; j < javaArray[i].length; j++) {
        javaArray[i][j] = "0";

        <?php 
        if(sizeof($javaArray) > 0)
        {
            ?>
            javaArray[i][j] = "<?php echo $phpArray[$i][$j]; ?>";
            <?php
        }
        ?>
    }
}

Any idea on how can I do this?

Thanks in advance for your time and effort! :)

Johanovski
  • 235
  • 1
  • 5
  • 15
  • 2
    echoing an array would not give you desired values. try to json_encode that array and then put that into javascript value then run the loop on that javascript value – Rohit Choudhary May 27 '13 at 11:31
  • 3
    Cant you just json encode it: `javaArray = ;`? – sroes May 27 '13 at 11:31
  • This won't work in this way. You have to understand the different between server side scripting and client side scripting languages. In your code the PHP code will be executed before it comes to the browser. Then the Javascript code will be executed. So you need to pass the PHP array to Javascript code via AJAX then process it. ""; Here i and j means nothing when executed at server side. – Nish May 27 '13 at 11:31
  • I was literally just about to answer with that @sroes - you should add it as an answer - got my upvote :) – LeonardChallis May 27 '13 at 11:32
  • Already answered in http://stackoverflow.com/questions/5618925/convert-php-array-to-javascript – Nish May 27 '13 at 11:36
  • The thing is that PHP is running on the server, whereas Javascript starts running on The client browser (after PHP code has been executed and finished). – piotr_cz May 27 '13 at 11:32

4 Answers4

6

You should use json_encode:

javaArray = <?php echo json_encode($phpArray) ?>;
sroes
  • 14,663
  • 1
  • 53
  • 72
  • Thanks sroes, it worked! I've marked it as 'accepted'! I'm having a weird behavior now: sometimes the 'javaArray' must be initiated full of '0' and sometimes it must be copied from the 'phpArray'. Then, it is "printed" inside an HTML textArea. When the javaArray is initialized full of '0', the textArea is filled with no extra space between the lines; however, when it is initialized through the 'phpArray', it is printed with a kind of 'double space' between lines. I've searched for strange characters inside the array but I didn't find anything... Any idea on what can be happening? Thanks! :) – Johanovski May 28 '13 at 08:22
  • How is `javaArray` printed inside the textarea? – sroes May 28 '13 at 08:48
  • Ouch! Nevermind, I've just found a spare "\n" printed in each line end... Now it works perfectly: thanks, sroes! :D – Johanovski May 28 '13 at 08:51
0

According to comments (why not use JSON encoding?) the connection between JS and PHP is only one-directional, so you need to create complete JS code in PHP.

I propose doing something like (one dimensional array for clarity):

// this is PHP code
echo "var JavaArray = array("; // this echoes declaration of JavaScript array
foreach($phpArray as $item){ // this starts iterating PHP array
  echo $item.', '; // this "copies" PHP array item to JavaScript array item
}
echo ')'; // close JS declaration of array

This in fact is not perfect, as it leaves , on the ending but you get the idea. All JS code needs to be output by PHP.

Voitcus
  • 4,463
  • 4
  • 24
  • 40
0

As suggested in the comments, this will work only if the javascript is generated from a .php page. If it's a .js script, it won't work.

The easiest way is

var javaArray = <?php echo json_encode($phpArray) ?>;

as suggested by others.

The reason why you're code didn't work is that you have a javascript cycle, not a PHP cycle. In PHP, you could do this:

var javaArray = [];
<?php
  for ($i=0; $i < count($phpArray); $i++) {
     for ($j=0; $j < count($phpArray[$i]); $j++) {
         echo "javaArray[$i][$j] = " . $javaArray[$i][$j] . ";";
     }
  }
?>
Mifeet
  • 12,949
  • 5
  • 60
  • 108
0

I don't do a great deal of PHP, but I would suspect that most folk would use a JSON function or library to create the text that assigns to a Javascript variable - you should look into that.

In your case, I can see what you are trying to do, but when you use you absolutely have to think of the PHP/server side as writing the script for the javascript side. You can't mix the two languages, because there's no way of keeping PHPs $i and $j in kilter with javascripts i and j.

To clarify, javascript's i and j come into scope on the client's machine long after $phpArray and $i and $j have gone out of scope on the server - 'never the twain shall meet' etc.

It looks like what you are trying to write is the array allocation and initialisation logic. There's no real problem with doing it this way for short loops. You code a loop in PHP, and write out code in Javascript. There will be no loop on the javascript side - just an 'unrolled' set of values.

e.g. if i and j go from 0 to 2, with digits 0 to 8, you'd write PHP code to output the following:

javaArray = new Array(2);
javaArray[0] = new Array(2);
javaArray[0][0] = 0;
javaArray[0][1] = 1;
javaArray[0][2] = 2;
javaArray[1] = new Array(2);
javaArray[1][0] = 3;
javaArray[1][1] = 4;
javaArray[1][2] = 5;
javaArray[2] = new Array(2);
javaArray[2][0] = 6;
javaArray[2][1] = 7;
javaArray[2][2] = 8;

Note again that during the initialisation, javascript does not have loops - those are on the PHP side. Once you have the data down though, you can loop over it or index into it using javascript in the browser (but not PHP).

Hope that this helps.

Mark ia.uk.com

Mark Rabjohn
  • 1,643
  • 14
  • 30
  • @Johanovski - see sroes answer, that's probably how you do the JSON thing in PHP then :) that will definitely be the best and most efficient way of passing the array to javascript. – Mark Rabjohn May 27 '13 at 11:47