Creating a javascript array with PHP json_encode

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

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

Open in new window

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
because json_encode is returning an object:

Only indexed arrays have a length property. Even it returned an associative array, it would still alert undefined
>>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";
alert(x.length); // ==> undefined

Zero if used with an array constructor
var x = new Array(); // or var x = []
x['firstname'] = "john";
alert(x.length); // ==> 0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.