0

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?

N3R4ZZuRR0
  • 2,400
  • 4
  • 18
  • 32

2 Answers2

3

The problem is you are executing this in global scope. There is already a name property on the global window object. This among other reasons is why people will tell you not to declare variables in the global scope.

What is happening is your array is getting coereced into a string value in order to save it into the window.name property and hence why doing name[i] retrieves a letter instead of a word.

Name your variable something else

var i;
var nameArr = <?php echo json_encode($array); ?>;
for(i=0;i<nameArr.length;i++){
    document.body.insertAdjacentHTML('beforeend',nameArr[i]+'<br>');
}

Also try not to use document.write there are other DOM methods/properties that you can use to insert html/text

Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
1

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>
MaxCloutier
  • 317
  • 2
  • 10