[javascript] PHP array() to javascript array()

I'm trying to convert a PHP array to a javascript array for jQuery's datetimepicker to disable some dates. But I can't seem to find the right answer on the internet. I'm using Zend Framework for my project.

<?php 
            $ConvertDateBack = Zend_Controller_Action_HelperBroker::getStaticHelper('ConvertDate');
            $disabledDaysRange = array();
            foreach($this->reservedDates as $dates) {
                 $date = $ConvertDateBack->ConvertDateBack($dates->reservation_date);
                 $disabledDaysRange[] = $date;
            }
?>
<script>
var disabledDaysRange = $disabledDaysRange ???? Please Help;
$(function() {
    function disableRangeOfDays(d) {
        for(var i = 0; i < disabledDaysRange.length; i++) {
            if($.isArray(disabledDaysRange[i])) {
                for(var j = 0; j < disabledDaysRange[i].length; j++) {
                    var r = disabledDaysRange[i][j].split(" to ");
                    r[0] = r[0].split("-");
                    r[1] = r[1].split("-");
                    if(new Date(r[0][2], (r[0][0]-1), r[0][1]) <= d && d <= new Date(r[1][2], (r[1][0]-1), r[1][1])) {
                        return [false];
                    }
                }
            }else{
                if(((d.getMonth()+1) + '-' + d.getDate() + '-' + d.getFullYear()) == disabledDaysRange[i]) {
                    return [false];
                }
            }
        }
        return [true];
    }
    $('#date').datepicker({
        dateFormat: 'dd/mm/yy',
        beforeShowDay: disableRangeOfDays
        });
});
</script>

This question is related to javascript php arrays

The answer is


The PHP json_encode function translates the data passed to it to a JSON string which can then be output to a JavaScript variable.The PHP json_encode function returns a string containing the JSON equivalent of the value passed to it.

<?php
$ar = array('apple', 'orange', 'banana', 'strawberry');
echo json_encode($ar); // ["apple","orange","banana","strawberry"]
?>

You can pass the JSON string output by json_encode to a JavaScript variable as follows:

<script type="text/javascript">
// pass PHP variable declared above to JavaScript variable
var ar = <?php echo json_encode($ar) ?>;
</script>

A numerically indexed PHP array is translated to an array literal in the JSON string. A JSON_FORCE_OBJECT option can be used if you want the array to be output as an object instead:

<?php
echo json_encode($ar, JSON_FORCE_OBJECT);
// {"0":"apple","1":"orange","2":"banana","3":"strawberry"} 
?>

Associative Array Example:

<?php
$book = array(
    "title" => "JavaScript: The Definitive Guide",
    "author" => "David Flanagan",
    "edition" => 6
);
?>
<script type="text/javascript">
var book = <?php echo json_encode($book, JSON_PRETTY_PRINT) ?>;
/* var book = {
    "title": "JavaScript: The Definitive Guide",
    "author": "David Flanagan",
    "edition": 6
}; */
alert(book.title);
</script>

Notice that PHP's associative array becomes an object literal in JavaScript. We use the JSON_PRETTY_PRINT option as the second argument to json_encode to display the output in a readable format.

You can access object properties using dot syntax, as displayed with the alert included above, or square bracket syntax: book['title'].

here you can find more information and details.


Have you tried using json_encode http://php.net/manual/en/function.json-encode.php

It converts an array to a json string


This may be a easy solution.

var mydate = '<?php implode("##",$youdateArray); ?>';
var ret = mydate.split("##");

 <script> var disabledDaysRange = $disabledDaysRange ???? Please Help;
 $(function() {
     function disableRangeOfDays(d) {

in the above assign array to javascript variable "disableDaysRange"

$disallowDates = "";
echo "[";
foreach($disabledDaysRange as $disableDates){
 $disallowDates .= "'".$disableDates."',";
}

echo substr(disallowDates,0,(strlen(disallowDates)-1)); // this will escape the last comma from $disallowDates
echo "];";

so your javascript var diableDateRange shoudl be 

var diableDateRange = ["2013-01-01","2013-01-02","2013-01-03"];

<?php 
  $ConvertDateBack = Zend_Controller_Action_HelperBroker::getStaticHelper('ConvertDate');
  $disabledDaysRange = array();
  foreach($this->reservedDates as $dates) {
    $date = $ConvertDateBack->ConvertDateBack($dates->reservation_date);
    $disabledDaysRange[] = $date;
  }
  $disDays = size($disabledDaysRange);
?>
<script>
var disabledDaysRange = {};
var disDays = '<?=$disDays;?>';
for(i=0;i<disDays;i++) {
  array.push(disabledDaysRange,'<?=$disabledDaysRange[' + i + '];?>');
}
............................

You should need to convert your PHP array to javascript array using PHP syntax json_encode. json_encode convert PHP array to JSON string

Single Dimension PHP array to javascript array

<?php
var $itemsarray= array("Apple", "Bear", "Cat", "Dog");
?>
<script>
var items= <?php echo json_encode($itemsarray); ?>;
console.log(items[2]); // Output: Bear
// OR
alert(items[0]); // Output: Apple
</script>

Multi Dimension PHP array to javascript array

<?php
var $itemsarray= array( 
               array('name'='Apple', 'price'=>'12345'),
               array('name'='Bear', 'price'=>'13344'),
               array('name'='Potato', 'price'=>'00440')
             );
?>


<script>
var items= <?php echo json_encode($itemsarray); ?>;
console.log(items[1][name]); // Output: Bear
// OR
alert(items[0][price]); // Output: Apple
</script>

For more detail, you can also check php array to javascript array


<?php 
            $ConvertDateBack = Zend_Controller_Action_HelperBroker::getStaticHelper('ConvertDate');
            $disabledDaysRange = array();
            foreach($this->reservedDates as $dates) {
                 $date = $ConvertDateBack->ConvertDateBack($dates->reservation_date);
                 $disabledDaysRange[] = $date;
                 array_push($disabledDaysRange, $date);
            }

            $finalArr = json_encode($disabledDaysRange);
?>
<script>
var disabledDaysRange = <?=$finalArr?>;

</script>

To convert you PHP array to JS , you can do it like this :

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

or using JSON_ENCODE :

var js_array =<?php echo json_encode($disabledDaysRange );?>;

Example without JSON_ENCODE:

<script type='text/javascript'>
    <?php
    $php_array = array('abc','def','ghi');
    ?>
    var js_array = [<?php echo '"'.implode('","', $php_array).'"' ?>];
    alert(js_array[0]);
</script>

Example with JSON_ENCODE :

<script type='text/javascript'>
    <?php
    $php_array = array('abc','def','ghi');
    ?>
    var js_array =<?php echo json_encode($disabledDaysRange );?>;
    alert(js_array[0]);
</script>

When we convert PHP array into JS array then we get all values in string. For example:

var ars= '<?php echo json_encode($abc); ?>';

The issue in above method is when we try to get the first element of ars[0] then it gives us bracket where as in we need first element as compare to bracket so the better way to this is

var packing_slip_orders = JSON.parse('<?php echo json_encode($packing_slip_orders); ?>');

You should use json_parse after json_encode to get the accurate array result.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?