Verma Jr. Verma Jr. - 6 months ago 14
PHP Question

While assigning a PHP array to a JS array, each alphabet of the values of the array gets split

This is the code:

<?php
$array = array('RANAJI', 'YAARA MAULA', 'AARAMBH', 'AISI SAZAA', 'SHEHER', 'BEEDO', 'DUNIYA', 'RAAT KE MUSAFIR');
foreach ($array as $item) echo $item.'<br>';
?>

<script>
var i;
var name = <?php echo json_encode($array); ?>;
for(i=0;i<name.length;i++){
document.write(name[i]+'<br>');
}
</script>


And this is the output:


RANAJI

YAARA MAULA

AARAMBH

AISI SAZAA

SHEHER

BEEDO

DUNIYA

RAAT KE MUSAFIR

R

A

N

A

J

I

,

Y

A

A

R

A

M

A

U

L

A

,

A

A

A

M

B

H

,

A

I

S

I

S

A

Z

A

A

,

S

H

E

H

E

R

,

B

E

E

D

O

,

D

U

N

I

Y

A

,

R

A

A

T

K

E

M

U

S

A

F

I

R


So, how to store the values in the same way as they are stored in the PHP array?

Answer

The variable 'name' is the problem, change it to something like 'foo' and it should work

<?php
$array = array('RANAJI', 'YAARA MAULA', 'AARAMBH', 'AISI SAZAA', 'SHEHER', 'BEEDO', 'DUNIYA', 'RAAT KE MUSAFIR');
foreach ($array as $item) echo $item.'<br>';
?>

<script>
var i;
var foo = <?php echo json_encode($array); ?>;
for(i=0;i<foo.length;i++){
document.write(foo[i]+'<br>');
}
</script>