Can you use php array in javascript?

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    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:

    GeeksforGeeks

    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.


    Data transfer between two platform requires a common data format. JSON is a common global format to send cross platform data.

    drawChart(600/50, JSON.parse('<?php echo json_encode($day); ?>'), JSON.parse('<?php echo json_encode($week); ?>'), JSON.parse('<?php echo json_encode($month); ?>'), JSON.parse('<?php echo json_encode(createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day'))))); ?>'))
    

    This is the answer to your question. The answer may look very complex. You can see a simple example describing the communication between server side and client side here

    $employee = array(
     "employee_id" => 10011,
       "Name" => "Nathan",
       "Skills" =>
        array(
               "analyzing",
               "documentation" =>
                array(
                  "desktop",
                    "mobile"
                 )
            )
    );
    

    Conversion to JSON format is required to send the data back to client application ie, JavaScript. PHP has a built in function json_encode(), which can convert any data to JSON format. The output of the json_encode function will be a string like this.

    {
        "employee_id": 10011,
        "Name": "Nathan",
        "Skills": {
            "0": "analyzing",
            "documentation": [
                "desktop",
                "mobile"
            ]
        }
    }
    

    On the client side, success function will get the JSON string. Javascript also have JSON parsing function JSON.parse() which can convert the string back to JSON object.

    $.ajax({
            type: 'POST',
            headers: {
                "cache-control": "no-cache"
            },
            url: "employee.php",
            async: false,
            cache: false,
            data: {
                employee_id: 10011
            },
            success: function (jsonString) {
                var employeeData = JSON.parse(jsonString); // employeeData variable contains employee array.
        });
    

    Can you pass PHP array to JavaScript?

    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.

    Can you use PHP variable in JavaScript?

    Inside the JavaScript, we can use the PHP tag to echo the PHP variable assigning it to a JavaScript variable. For example, assign a value Metallica to a variable $var inside the PHP tags. Write a script tag and inside it, write a PHP tag. Inside the PHP tag, echo a JavaScript variable jsvar .

    Can we use array in JavaScript?

    In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable.

    Can I put an array in an array JavaScript?

    Introduction to JavaScript multidimensional array JavaScript does not provide the multidimensional array natively. However, you can create a multidimensional array by defining an array of elements, where each element is also another array.