Jesús Cruz
Jesús Cruz

Reputation: 192

Access a PHP array element by using a JavaScript variable as index

The code looks like this:

PHP file

<?php
...
$arrayName = ['ArrayValue_0', ..., 'ArrayValue_n'];
...
php?>

JavaScript

$('.elementClass').each(function(index, id) {
    $(id).html('<?php echo $arrayName[index - 1]?>');
});

But you can't just insert a JavaScript variable like that into php tags so index is never received. I know this can be done via AJAX but is there any other way? Thanks in advance.

Additional info: I've been told to do this in PHP so there's no posibility of switching the array to a JS file.

Upvotes: 1

Views: 5822

Answers (3)

VisioN
VisioN

Reputation: 145398

You can define arrayName variable in JS and initialize it with the value from the server:

var arrayName = <?php echo json_encode($arrayName); ?>;
$(".elementClass").each(function(index, id) {
    $(id).html(arrayName[index-1]);
});

Upvotes: 8

MMM
MMM

Reputation: 7310

What you're trying to do will not work. For example this:

$(id).html('<?php echo $arrayName[index - 1]?>');

The above will never, ever work, because PHP is run on a server, not on your user's browser.

What you need to do is send the variable somehow to the server. You have a plethora of options:

  1. Use a form and read a $_POST variable
  2. Append it to a URL and read a $_GET variable
  3. Use AJAX and asynchronously send that variable to the server
  4. Return the whole array from PHP to your Javascript code
  5. etc. etc.

Remember, PHP runs on the server, which renders the page, which then in turn is read by your browser where you run Javascript. You can't paste PHP code into the page and expect it to be parsed by PHP!

Upvotes: 1

Laurent S.
Laurent S.

Reputation: 6946

You need to get back to the server if you wish to get info from it (PhP runs on the server), so either you create a javascript variable on-the-fly when loading the page with the complete content of your PhP array , either you use ajax to get back to the server without refreshing the whole page.

Upvotes: 0

Related Questions