Santosh Gadhave Santosh Gadhave - 22 days ago 6
Javascript Question

Unusual behavior of php implode in javascript

I have been using PHP to get value from the database and storing them in an array and when I echo the code using implode in PHP, it is working absolutely fine(For single as well as multiple values in the data arrays.

PHP Code for Reference



$data_Sad= array();
$data_Like = array();

$data_Sad[] = 3;
//$data_Sad[] = 3;
$data_Like[] = 3;
//$data_Like[] = 3;


Now,

I want to assign that value to the javascript array. All i do is -

<script>
js_array = new Array(<?php echo implode(',', $data_Sad);?>);
js_array1 = new Array(<?php echo implode(',', $data_Like); ?>);

alert(js_array);
alert(js_array1);
</script>


Now when I alert the js_array when it has single value then it simply returns/alerts an empty array string. While when I populate 2 or more values then it works perfectly fine.

Also, if I use json_encode then it works fine but again it is a string format output and all I need is int/number values.

Can anyone help me out solving the issue using implode of PHP or any other work around?



Thanks in anticipation :)

Answer Source

Try run the below code and you will understand the problem.

<?php

$data_Sad= array();
$data_Like = array();

$data_Sad[] = 3;
$data_Sad[] = 4;
//$data_Sad[] = 3;
$data_Like[] = 3;
$data_Like[] = 5;
//$data_Like[] = 3;
echo "<pre>";print_r($data_Sad);print_r($data_Like);echo "</pre>";
?>
<script>    
js_array = new Array(<?php echo implode(',', $data_Sad);?>);
js_array1  = new Array(<?php echo implode(',', $data_Like); ?>);

alert(js_array);
alert(js_array1);
</script>

When PHP array has one numeric value, it will taking as array initialization.

To avoid such issues, use the below code.

<?php

$data_Sad= array();
$data_Like = array();

$data_Sad[] = 3;    
//$data_Sad[] = 3;
$data_Like[] = 3;    
//$data_Like[] = 3;
echo "<pre>";print_r($data_Sad);print_r($data_Like);echo "</pre>";
?>
<script>    
js_array = new Array(<?php echo '\''.implode('\',\'', $data_Sad).'\'';?>);
js_array1  = new Array(<?php echo '\''.implode('\',\'', $data_Like).'\''; ?>);

alert(js_array);
alert(js_array1);
</script>