We help IT Professionals succeed at work.

Creating a javascript array with PHP json_encode

Anyone have any idea why this would come up as undefined?


<?php
	    
		$patients = array(
			    		   'fn' => 'Bobby',
			               'ln' => 'Jones'
						  );
		
		echo '<script type="text/javascript">var patients = (' .  json_encode($patients)  . '); alert(patients.length);</script>';
		
	?>

Open in new window

Comment
Watch Question

Commented:
javascript is client side programming,

PHP is server side.

you can't mix them.

you can't define an array in php and call it in javascript.

just doesn't work that way.
CERTIFIED EXPERT
Expert of the Year 2008
Top Expert 2008

Commented:
because json_encode is returning an object:
{"fn":"Bobby","ln":"Jones"};

Only indexed arrays have a length property. Even it returned an associative array, it would still alert undefined
CERTIFIED EXPERT
Expert of the Year 2008
Top Expert 2008
Commented:
>>Even if it were to return an associative array, it would still alert undefined
Well, "undefined" if declared with an Object constructor:
var x = new Object(); // or var x = {}
x['firstname'] = "john";
x['lastname']='doe';
alert(x.length); // ==> undefined

Zero if used with an array constructor
var x = new Array(); // or var x = []
x['firstname'] = "john";
x['lastname']='doe';
alert(x.length); // ==> 0

Explore More ContentExplore courses, solutions, and other research materials related to this topic.