Friday, October 24, 2025
HomeLanguagesHow to pass a PHP array to a JavaScript function?

How to pass a PHP array to a JavaScript function?

Passing PHP Arrays to JavaScript is very easy by using JavaScript Object Notation(JSON).

Method 1: Using json_encode() function: The json_encode() function is used to return the JSON representation of a value or array. The function can take both single dimensional and multidimensional arrays.

Steps:

  • Creating an array in PHP:
    <?php
    $sampleArray = array(
            0 => "Geeks", 
            1 => "for", 
            2 => "Geeks", 
        );
    ?>
    
  • Using json_encode() function to retrieve the array elements
    var passedArray = <?php echo json_encode($sampleArray); ?>;

Example:




<?php
     
// Create an array
$sampleArray = array(
    0 => "Geeks", 
    1 => "for", 
    2 => "Geeks", 
)
?>
   
<script>
  
// Access the array elements
var passedArray = 
    <?php echo json_encode($sampleArray); ?>;
       
// Display the array elements
for(var i = 0; i < passedArray.length; i++){
    document.write(passedArray[i]);
}
</script>


Output:

neveropen

Method 2: Using PHP implode() function: The implode() is used to join the elements of an array. The implode() function is the alias of join() function and works exactly same as that of join() function.
The implode() function is used to build a string that becomes an array literal in JavaScript. So, if we have an array in PHP, we can pass it to JavaScript as follows:

var passedArray = <?php echo '["' . implode('", "', $sampleArray) . '"]' ?>;

Example:




<?php
  
// Creating a PHP Array
$sampleArray = array('Car', 'Bike', 'Boat');
  
?>
  
<script type="text/javascript">
   
// Using PHP implode() function
var passedArray = 
    <?php echo '["' . implode('", "', $sampleArray) . '"]' ?>;
   
// Printing the passed array elements
document.write(passedArray);
   
</script>


Output:

Car, Bike, Boat

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS