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?

7
  • Then what is your question ? Commented May 31, 2016 at 19:18
  • How to store the values in the same way as they are stored in the PHP array? Commented May 31, 2016 at 19:21
  • What is the result of the output HTML from the PHP file? It seems to treat it like a concatenated string in the Javascript for-loop. Commented May 31, 2016 at 19:27
  • @kb. The output in the question is what that HTML page is giving. Commented May 31, 2016 at 19:30
  • @VermaJr. I am talking about the actual HTML source that is returned by the server, it will not contain the <?php but rather the result of the echo. (But nevermind :), seems like it was a scope issue.) Commented May 31, 2016 at 19:34

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.